/
FbBatchExecution.cs
632 lines (553 loc) · 20.4 KB
/
FbBatchExecution.cs
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
/*
* The contents of this file are subject to the Initial
* Developer's Public License Version 1.0 (the "License");
* you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
* https://github.com/FirebirdSQL/NETProvider/blob/master/license.txt.
*
* Software distributed under the License is distributed on
* an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either
* express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* All Rights Reserved.
*/
//$Authors = Abel Eduardo Pereira, Jiri Cincura (jiri@cincura.net), Olivier Metod
using System;
using System.Data;
using System.Linq;
using System.Globalization;
using FirebirdSql.Data.FirebirdClient;
namespace FirebirdSql.Data.Isql
{
public class FbBatchExecution
{
/// <summary>
/// The event trigged before a SQL statement goes for execution.
/// </summary>
public event EventHandler<CommandExecutingEventArgs> CommandExecuting;
/// <summary>
/// The event trigged after a SQL statement execution.
/// </summary>
public event EventHandler<CommandExecutedEventArgs> CommandExecuted;
FbStatementCollection _statements;
FbConnection _sqlConnection;
FbTransaction _sqlTransaction;
FbConnectionStringBuilder _connectionString;
FbCommand _sqlCommand;
// control fields
bool _requiresNewConnection;
bool _shouldClose;
/// <summary>
/// Represents the list of SQL statements for batch execution.
/// </summary>
public FbStatementCollection Statements
{
get { return _statements; }
}
/// <summary>
/// Creates an instance of FbBatchExecution engine with the given
/// connection.
/// </summary>
/// <param name="sqlConnection">A <see cref="FbConnection"/> object.</param>
public FbBatchExecution(FbConnection sqlConnection = null)
{
_statements = new FbStatementCollection();
if (sqlConnection == null)
{
_sqlConnection = new FbConnection(); // do not specify the connection string
_connectionString = new FbConnectionStringBuilder();
}
else
{
_sqlConnection = sqlConnection;
_connectionString = new FbConnectionStringBuilder(sqlConnection.ConnectionString);
}
}
/// <summary>
/// Appends SQL statements from <see cref="FbScript"/> instance. <see cref="FbScript.Parse"/> should be already called.
/// </summary>
/// <param name="isqlScript">A <see cref="FbScript"/> object.</param>
public void AppendSqlStatements(FbScript isqlScript)
{
_statements.AddRange(isqlScript.Results);
}
/// <summary>
/// Starts the ordered execution of the SQL statements that are in <see cref="SqlStatements"/> collection.
/// </summary>
/// <param name="autoCommit">Specifies if the transaction should be committed after a DDL command execution</param>
public void Execute(bool autoCommit = true)
{
if ((_statements?.Count ?? 0) == 0)
{
throw new InvalidOperationException("There are no commands for execution.");
}
_shouldClose = false;
foreach (var statement in Statements)
{
if (!(statement.StatementType == SqlStatementType.Connect ||
statement.StatementType == SqlStatementType.CreateDatabase ||
statement.StatementType == SqlStatementType.Disconnect ||
statement.StatementType == SqlStatementType.DropDatabase ||
statement.StatementType == SqlStatementType.SetAutoDDL ||
statement.StatementType == SqlStatementType.SetDatabase ||
statement.StatementType == SqlStatementType.SetNames ||
statement.StatementType == SqlStatementType.SetSQLDialect))
{
ProvideCommand();
_sqlCommand.CommandText = statement.Text;
if (_sqlTransaction == null && !(statement.StatementType == SqlStatementType.Commit || statement.StatementType == SqlStatementType.Rollback))
{
_sqlTransaction = _sqlConnection.BeginTransaction();
}
_sqlCommand.Transaction = _sqlTransaction;
}
try
{
switch (statement.StatementType)
{
case SqlStatementType.AlterCharacterSet:
case SqlStatementType.AlterDatabase:
case SqlStatementType.AlterDomain:
case SqlStatementType.AlterException:
case SqlStatementType.AlterFunction:
case SqlStatementType.AlterIndex:
case SqlStatementType.AlterPackage:
case SqlStatementType.AlterProcedure:
case SqlStatementType.AlterRole:
case SqlStatementType.AlterSequence:
case SqlStatementType.AlterTable:
case SqlStatementType.AlterTrigger:
case SqlStatementType.AlterView:
case SqlStatementType.CommentOn:
case SqlStatementType.CreateCollation:
case SqlStatementType.CreateDomain:
case SqlStatementType.CreateException:
case SqlStatementType.CreateFunction:
case SqlStatementType.CreateGenerator:
case SqlStatementType.CreateIndex:
case SqlStatementType.CreatePackage:
case SqlStatementType.CreatePackageBody:
case SqlStatementType.CreateProcedure:
case SqlStatementType.CreateRole:
case SqlStatementType.CreateSequence:
case SqlStatementType.CreateShadow:
case SqlStatementType.CreateTable:
case SqlStatementType.CreateTrigger:
case SqlStatementType.CreateView:
case SqlStatementType.DeclareCursor:
case SqlStatementType.DeclareExternalFunction:
case SqlStatementType.DeclareFilter:
case SqlStatementType.DeclareStatement:
case SqlStatementType.DeclareTable:
case SqlStatementType.Delete:
case SqlStatementType.DropCollation:
case SqlStatementType.DropDomain:
case SqlStatementType.DropException:
case SqlStatementType.DropExternalFunction:
case SqlStatementType.DropFunction:
case SqlStatementType.DropFilter:
case SqlStatementType.DropGenerator:
case SqlStatementType.DropIndex:
case SqlStatementType.DropProcedure:
case SqlStatementType.DropSequence:
case SqlStatementType.DropRole:
case SqlStatementType.DropShadow:
case SqlStatementType.DropTable:
case SqlStatementType.DropTrigger:
case SqlStatementType.DropView:
case SqlStatementType.EventInit:
case SqlStatementType.EventWait:
case SqlStatementType.Execute:
case SqlStatementType.ExecuteImmediate:
case SqlStatementType.ExecuteProcedure:
case SqlStatementType.Grant:
case SqlStatementType.Insert:
case SqlStatementType.InsertCursor:
case SqlStatementType.Open:
case SqlStatementType.Prepare:
case SqlStatementType.Revoke:
case SqlStatementType.RecreateFunction:
case SqlStatementType.RecreatePackage:
case SqlStatementType.RecreatePackageBody:
case SqlStatementType.RecreateProcedure:
case SqlStatementType.RecreateTable:
case SqlStatementType.RecreateTrigger:
case SqlStatementType.RecreateView:
case SqlStatementType.SetGenerator:
case SqlStatementType.Update:
case SqlStatementType.Whenever:
OnCommandExecuting(_sqlCommand, statement.StatementType);
var rowsAffected = ExecuteCommand(autoCommit);
_requiresNewConnection = false;
OnCommandExecuted(null, statement.Text, statement.StatementType, rowsAffected);
break;
case SqlStatementType.ExecuteBlock:
case SqlStatementType.Select:
#warning Who's disposing this?
ProvideCommand().CommandText = statement.Text;
OnCommandExecuting(_sqlCommand, statement.StatementType);
using (var dataReader = _sqlCommand.ExecuteReader())
{
_requiresNewConnection = false;
OnCommandExecuted(dataReader, statement.Text, statement.StatementType, -1);
}
break;
case SqlStatementType.Commit:
OnCommandExecuting(null, statement.StatementType);
CommitTransaction();
OnCommandExecuted(null, statement.Text, statement.StatementType, -1);
break;
case SqlStatementType.Rollback:
OnCommandExecuting(null, statement.StatementType);
RollbackTransaction();
OnCommandExecuted(null, statement.Text, statement.StatementType, -1);
break;
case SqlStatementType.CreateDatabase:
OnCommandExecuting(null, statement.StatementType);
CreateDatabase(statement.CleanText);
_requiresNewConnection = false;
OnCommandExecuted(null, statement.Text, statement.StatementType, -1);
break;
case SqlStatementType.DropDatabase:
OnCommandExecuting(null, statement.StatementType);
FbConnection.DropDatabase(_connectionString.ToString());
_requiresNewConnection = true;
OnCommandExecuted(null, statement.Text, statement.StatementType, -1);
break;
case SqlStatementType.Connect:
OnCommandExecuting(null, statement.StatementType);
ConnectToDatabase(statement.CleanText);
_requiresNewConnection = false;
OnCommandExecuted(null, statement.Text, statement.StatementType, -1);
break;
case SqlStatementType.Disconnect:
OnCommandExecuting(null, statement.StatementType);
_sqlConnection.Close();
FbConnection.ClearPool(_sqlConnection);
_requiresNewConnection = false;
OnCommandExecuted(null, statement.Text, statement.StatementType, -1);
break;
case SqlStatementType.SetAutoDDL:
OnCommandExecuting(null, statement.StatementType);
SetAutoDdl(statement.CleanText, ref autoCommit);
_requiresNewConnection = false;
OnCommandExecuted(null, statement.Text, statement.StatementType, -1);
break;
case SqlStatementType.SetNames:
OnCommandExecuting(null, statement.StatementType);
SetNames(statement.CleanText);
_requiresNewConnection = true;
OnCommandExecuted(null, statement.Text, statement.StatementType, -1);
break;
case SqlStatementType.SetSQLDialect:
OnCommandExecuting(null, statement.StatementType);
SetSqlDialect(statement.CleanText);
_requiresNewConnection = true;
OnCommandExecuted(null, statement.Text, statement.StatementType, -1);
break;
case SqlStatementType.Fetch:
case SqlStatementType.Describe:
break;
case SqlStatementType.SetDatabase:
case SqlStatementType.SetStatistics:
case SqlStatementType.SetTransaction:
case SqlStatementType.ShowSQLDialect:
throw new NotImplementedException();
}
}
catch (Exception ex)
{
RollbackTransaction();
CloseConnection();
throw new FbException(string.Format("An exception was thrown when executing command: {1}.{0}Batch execution aborted.{0}The returned message was: {2}.",
Environment.NewLine,
statement.Text,
ex.Message),
ex);
}
}
CommitTransaction();
CloseConnection();
}
/// <summary>
/// Updates the connection string with the data parsed from the parameter and opens a connection
/// to the database.
/// </summary>
/// <param name="connectDbStatement"></param>
protected void ConnectToDatabase(string connectDbStatement)
{
// CONNECT 'filespec'
// [USER 'username']
// [PASSWORD 'password']
// [CACHE int]
// [ROLE 'rolename']
SqlStringParser parser = new SqlStringParser(connectDbStatement);
parser.Tokens = new[] { " ", "\r\n", "\n", "\r" };
using (var enumerator = parser.Parse().GetEnumerator())
{
enumerator.MoveNext();
if (enumerator.Current.Text.ToUpperInvariant() != "CONNECT")
{
throw new ArgumentException("Malformed isql CONNECT statement. Expected keyword CONNECT but something else was found.");
}
enumerator.MoveNext();
_connectionString.Database = enumerator.Current.Text.Replace("'", string.Empty);
while (enumerator.MoveNext())
{
switch (enumerator.Current.Text.ToUpperInvariant())
{
case "USER":
enumerator.MoveNext();
_connectionString.UserID = enumerator.Current.Text.Replace("'", string.Empty);
break;
case "PASSWORD":
enumerator.MoveNext();
_connectionString.Password = enumerator.Current.Text.Replace("'", string.Empty);
break;
case "CACHE":
enumerator.MoveNext();
break;
case "ROLE":
enumerator.MoveNext();
_connectionString.Role = enumerator.Current.Text.Replace("'", string.Empty);
break;
default:
throw new ArgumentException("Unexpected token '" + enumerator.Current.Text + "' on isql CONNECT statement.");
}
}
}
_requiresNewConnection = true;
ProvideConnection();
}
/// <summary>
/// Parses the isql statement CREATE DATABASE and creates the database and opens a connection to the recently created database.
/// </summary>
/// <param name="createDatabaseStatement">The create database statement.</param>
protected void CreateDatabase(string createDatabaseStatement)
{
// CREATE {DATABASE | SCHEMA} 'filespec'
// [USER 'username' [PASSWORD 'password']]
// [PAGE_SIZE [=] int]
// [LENGTH [=] int [PAGE[S]]]
// [DEFAULT CHARACTER SET charset]
// [<secondary_file>];
int pageSize = 0;
SqlStringParser parser = new SqlStringParser(createDatabaseStatement);
parser.Tokens = new[] { " ", "\r\n", "\n", "\r" };
using (var enumerator = parser.Parse().GetEnumerator())
{
enumerator.MoveNext();
if (enumerator.Current.Text.ToUpperInvariant() != "CREATE")
{
throw new ArgumentException("Malformed isql CREATE statement. Expected keyword CREATE but something else was found.");
}
enumerator.MoveNext(); // {DATABASE | SCHEMA}
enumerator.MoveNext();
_connectionString.Database = enumerator.Current.Text.Replace("'", string.Empty);
while (enumerator.MoveNext())
{
switch (enumerator.Current.Text.ToUpperInvariant())
{
case "USER":
enumerator.MoveNext();
_connectionString.UserID = enumerator.Current.Text.Replace("'", string.Empty);
break;
case "PASSWORD":
enumerator.MoveNext();
_connectionString.Password = enumerator.Current.Text.Replace("'", string.Empty);
break;
case "PAGE_SIZE":
enumerator.MoveNext();
if (enumerator.Current.Text == "=")
enumerator.MoveNext();
int.TryParse(enumerator.Current.Text, out pageSize);
break;
case "DEFAULT":
enumerator.MoveNext();
if (enumerator.Current.Text.ToUpperInvariant() != "CHARACTER")
throw new ArgumentException("Expected the keyword CHARACTER but something else was found.");
enumerator.MoveNext();
if (enumerator.Current.Text.ToUpperInvariant() != "SET")
throw new ArgumentException("Expected the keyword SET but something else was found.");
enumerator.MoveNext();
_connectionString.Charset = enumerator.Current.Text;
break;
}
}
}
FbConnection.CreateDatabase(_connectionString.ToString(), pageSize, true, false);
_requiresNewConnection = true;
ProvideConnection();
}
/// <summary>
/// Parses the isql statement SET AUTODDL and sets the character set to current connection string.
/// </summary>
/// <param name="setAutoDdlStatement">The set names statement.</param>
protected void SetAutoDdl(string setAutoDdlStatement, ref bool autoCommit)
{
// SET AUTODDL [ON | OFF]
SqlStringParser parser = new SqlStringParser(setAutoDdlStatement);
parser.Tokens = new[] { " ", "\r\n", "\n", "\r" };
using (var enumerator = parser.Parse().GetEnumerator())
{
enumerator.MoveNext();
if (enumerator.Current.Text.ToUpperInvariant() != "SET")
{
throw new ArgumentException("Malformed isql SET statement. Expected keyword SET but something else was found.");
}
enumerator.MoveNext(); // AUTO
if (enumerator.MoveNext())
{
string onOff = enumerator.Current.Text.ToUpperInvariant();
if (onOff == "ON")
{
autoCommit = true;
}
else if (onOff == "OFF")
{
autoCommit = false;
}
else
{
throw new ArgumentException("Expected the ON or OFF but something else was found.");
}
}
else
{
autoCommit = !autoCommit;
}
}
}
/// <summary>
/// Parses the isql statement SET NAMES and sets the character set to current connection string.
/// </summary>
/// <param name="setNamesStatement">The set names statement.</param>
protected void SetNames(string setNamesStatement)
{
// SET NAMES charset
SqlStringParser parser = new SqlStringParser(setNamesStatement);
parser.Tokens = new[] { " ", "\r\n", "\n", "\r" };
using (var enumerator = parser.Parse().GetEnumerator())
{
enumerator.MoveNext();
if (enumerator.Current.Text.ToUpperInvariant() != "SET")
{
throw new ArgumentException("Malformed isql SET statement. Expected keyword SET but something else was found.");
}
enumerator.MoveNext(); // NAMES
enumerator.MoveNext();
_connectionString.Charset = enumerator.Current.Text;
}
}
/// <summary>
/// Parses the isql statement SET SQL DIALECT and sets the dialect set to current connection string.
/// </summary>
/// <param name="setSqlDialectStatement">The set sql dialect statement.</param>
protected void SetSqlDialect(string setSqlDialectStatement)
{
// SET SQL DIALECT dialect
SqlStringParser parser = new SqlStringParser(setSqlDialectStatement);
parser.Tokens = new[] { " ", "\r\n", "\n", "\r" };
using (var enumerator = parser.Parse().GetEnumerator())
{
enumerator.MoveNext();
if (enumerator.Current.Text.ToUpperInvariant() != "SET")
{
throw new ArgumentException("Malformed isql SET statement. Expected keyword SET but something else was found.");
}
enumerator.MoveNext(); // SQL
enumerator.MoveNext(); // DIALECT
enumerator.MoveNext();
int.TryParse(enumerator.Current.Text, out var dialect);
_connectionString.Dialect = dialect;
}
}
protected FbCommand ProvideCommand()
{
if (_sqlCommand == null)
{
_sqlCommand = new FbCommand();
}
_sqlCommand.Connection = ProvideConnection();
return _sqlCommand;
}
protected FbConnection ProvideConnection()
{
if (_requiresNewConnection)
{
if (_sqlConnection != null && _sqlConnection.State != ConnectionState.Closed)
{
CloseConnection();
}
_sqlConnection = new FbConnection(_connectionString.ToString());
}
if (_sqlConnection.State == ConnectionState.Closed)
{
_sqlConnection.Open();
_shouldClose = true;
}
return _sqlConnection;
}
/// <summary>
/// Executes a command and optionally commits the transaction.
/// </summary>
/// <param name="command">Command to execute.</param>
/// <param name="autocommit">true to commit the transaction after execution; or false if not.</param>
/// <returns>The number of rows affected by the query execution.</returns>
protected int ExecuteCommand(bool autoCommit)
{
int rowsAffected = _sqlCommand.ExecuteNonQuery();
if (autoCommit && _sqlCommand.IsDDLCommand)
{
CommitTransaction();
}
return rowsAffected;
}
protected void CommitTransaction()
{
if (_sqlTransaction != null)
{
_sqlTransaction.Commit();
_sqlTransaction = null;
}
}
protected void RollbackTransaction()
{
if (_sqlTransaction != null)
{
_sqlTransaction.Rollback();
_sqlTransaction = null;
}
}
protected void CloseConnection()
{
if (_shouldClose)
{
_sqlConnection.Close();
}
}
/// <summary>
/// The trigger function for <see cref="CommandExecuting"/> event.
/// </summary>
/// <param name="sqlCommand">The SQL command that is going for execution.</param>
protected void OnCommandExecuting(FbCommand sqlCommand, SqlStatementType statementType)
{
CommandExecuting?.Invoke(this, new CommandExecutingEventArgs(sqlCommand, statementType));
}
/// <summary>
/// The trigger function for <see cref="CommandExecuted"/> event.
/// </summary>
/// <param name="commandText">The <see cref="FbCommand.CommandText"/> of the executed SQL command.</param>
/// <param name="dataReader">The <see cref="FbDataReader"/> instance with the returned data. If the
/// command executed is not meant to return data (ex: UPDATE, INSERT...) this parameter must be
/// setled to <b>null</b>.</param>
/// <param name="rowsAffected">The rows that were affected by the executed SQL command. If the executed
/// command is not meant to return this kind of information (ex: SELECT) this parameter must
/// be setled to <b>-1</b>.</param>
protected void OnCommandExecuted(FbDataReader dataReader, string commandText, SqlStatementType statementType, int rowsAffected)
{
CommandExecuted?.Invoke(this, new CommandExecutedEventArgs(dataReader, commandText, statementType, rowsAffected));
}
}
}