-
Notifications
You must be signed in to change notification settings - Fork 139
/
PetaPoco.cs
4286 lines (3742 loc) · 139 KB
/
PetaPoco.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
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* PetaPoco - A Tiny ORMish thing for your POCO's.
* Copyright © 2011-2012 Topten Software. All Rights Reserved.
*
* Apache License 2.0 - http://www.toptensoftware.com/petapoco/license
*
* Special thanks to Rob Conery (@robconery) for original inspiration (ie:Massive) and for
* use of Subsonic's T4 templates, Rob Sullivan (@DataChomp) for hard core DBA advice
* and Adam Schroder (@schotime) for lots of suggestions, improvements and Oracle support
*/
// Define PETAPOCO_NO_DYNAMIC in your project settings on .NET 3.5
// This file was built by merging separate C# source files into one.
// DO NOT EDIT THIS FILE - go back to the originals
using PetaPoco.DatabaseTypes;
using PetaPoco.Internal;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
namespace PetaPoco
{
/// <summary>
/// The main PetaPoco Database class. You can either use this class directly, or derive from it.
/// </summary>
public class Database : IDisposable
{
#region Constructors
/// <summary>
/// Construct a database using a supplied IDbConnection
/// </summary>
/// <param name="connection">The IDbConnection to use</param>
/// <remarks>
/// The supplied IDbConnection will not be closed/disposed by PetaPoco - that remains
/// the responsibility of the caller.
/// </remarks>
public Database(IDbConnection connection)
{
_sharedConnection = connection;
_connectionString = connection.ConnectionString;
_sharedConnectionDepth = 2; // Prevent closing external connection
CommonConstruct();
}
/// <summary>
/// Construct a database using a supplied connections string and optionally a provider name
/// </summary>
/// <param name="connectionString">The DB connection string</param>
/// <param name="providerName">The name of the DB provider to use</param>
/// <remarks>
/// PetaPoco will automatically close and dispose any connections it creates.
/// </remarks>
public Database(string connectionString, string providerName)
{
_connectionString = connectionString;
_providerName = providerName;
CommonConstruct();
}
/// <summary>
/// Construct a Database using a supplied connection string and a DbProviderFactory
/// </summary>
/// <param name="connectionString">The connection string to use</param>
/// <param name="provider">The DbProviderFactory to use for instantiating IDbConnection's</param>
public Database(string connectionString, DbProviderFactory provider)
{
_connectionString = connectionString;
_factory = provider;
CommonConstruct();
}
/// <summary>
/// Construct a Database using a supplied connectionString Name. The actual connection string and provider will be
/// read from app/web.config.
/// </summary>
/// <param name="connectionStringName">The name of the connection</param>
public Database(string connectionStringName)
{
// Use first?
if (connectionStringName == "")
connectionStringName = ConfigurationManager.ConnectionStrings[0].Name;
// Work out connection string and provider name
var providerName = "System.Data.SqlClient";
if (ConfigurationManager.ConnectionStrings[connectionStringName] != null)
{
if (!string.IsNullOrEmpty(ConfigurationManager.ConnectionStrings[connectionStringName].ProviderName))
providerName = ConfigurationManager.ConnectionStrings[connectionStringName].ProviderName;
}
else
{
throw new InvalidOperationException("Can't find a connection string with the name '" + connectionStringName + "'");
}
// Store factory and connection string
_connectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
_providerName = providerName;
CommonConstruct();
}
/// <summary>
/// Provides common initialization for the various constructors
/// </summary>
private void CommonConstruct()
{
// Reset
_transactionDepth = 0;
EnableAutoSelect = true;
EnableNamedParams = true;
// If a provider name was supplied, get the IDbProviderFactory for it
if (_providerName != null)
_factory = DbProviderFactories.GetFactory(_providerName);
// Resolve the DB Type
string DBTypeName = (_factory == null ? _sharedConnection.GetType() : _factory.GetType()).Name;
_dbType = DatabaseType.Resolve(DBTypeName, _providerName);
// What character is used for delimiting parameters in SQL
_paramPrefix = _dbType.GetParameterPrefix(_connectionString);
}
#endregion
#region IDisposable
/// <summary>
/// Automatically close one open shared connection
/// </summary>
public void Dispose()
{
// Automatically close one open connection reference
// (Works with KeepConnectionAlive and manually opening a shared connection)
CloseSharedConnection();
}
#endregion
#region Connection Management
/// <summary>
/// When set to true the first opened connection is kept alive until this object is disposed
/// </summary>
public bool KeepConnectionAlive
{
get;
set;
}
/// <summary>
/// Open a connection that will be used for all subsequent queries.
/// </summary>
/// <remarks>
/// Calls to Open/CloseSharedConnection are reference counted and should be balanced
/// </remarks>
public void OpenSharedConnection()
{
if (_sharedConnectionDepth == 0)
{
_sharedConnection = _factory.CreateConnection();
_sharedConnection.ConnectionString = _connectionString;
if (_sharedConnection.State == ConnectionState.Broken)
_sharedConnection.Close();
if (_sharedConnection.State == ConnectionState.Closed)
_sharedConnection.Open();
_sharedConnection = OnConnectionOpened(_sharedConnection);
if (KeepConnectionAlive)
_sharedConnectionDepth++; // Make sure you call Dispose
}
_sharedConnectionDepth++;
}
/// <summary>
/// Releases the shared connection
/// </summary>
public void CloseSharedConnection()
{
if (_sharedConnectionDepth > 0)
{
_sharedConnectionDepth--;
if (_sharedConnectionDepth == 0)
{
OnConnectionClosing(_sharedConnection);
_sharedConnection.Dispose();
_sharedConnection = null;
}
}
}
/// <summary>
/// Provides access to the currently open shared connection (or null if none)
/// </summary>
public IDbConnection Connection
{
get { return _sharedConnection; }
}
#endregion
#region Transaction Management
// Helper to create a transaction scope
/// <summary>
/// Starts or continues a transaction.
/// </summary>
/// <returns>An ITransaction reference that must be Completed or disposed</returns>
/// <remarks>
/// This method makes management of calls to Begin/End/CompleteTransaction easier.
///
/// The usage pattern for this should be:
///
/// using (var tx = db.GetTransaction())
/// {
/// // Do stuff
/// db.Update(...);
///
/// // Mark the transaction as complete
/// tx.Complete();
/// }
///
/// Transactions can be nested but they must all be completed otherwise the entire
/// transaction is aborted.
/// </remarks>
public ITransaction GetTransaction()
{
return new Transaction(this);
}
/// <summary>
/// Called when a transaction starts. Overridden by the T4 template generated database
/// classes to ensure the same DB instance is used throughout the transaction.
/// </summary>
public virtual void OnBeginTransaction()
{
}
/// <summary>
/// Called when a transaction ends.
/// </summary>
public virtual void OnEndTransaction()
{
}
/// <summary>
/// Starts a transaction scope, see GetTransaction() for recommended usage
/// </summary>
public void BeginTransaction()
{
_transactionDepth++;
if (_transactionDepth == 1)
{
OpenSharedConnection();
_transaction = _sharedConnection.BeginTransaction();
_transactionCancelled = false;
OnBeginTransaction();
}
}
/// <summary>
/// Internal helper to cleanup transaction
/// </summary>
void CleanupTransaction()
{
OnEndTransaction();
if (_transactionCancelled)
_transaction.Rollback();
else
_transaction.Commit();
_transaction.Dispose();
_transaction = null;
CloseSharedConnection();
}
/// <summary>
/// Aborts the entire outer most transaction scope
/// </summary>
/// <remarks>
/// Called automatically by Transaction.Dispose()
/// if the transaction wasn't completed.
/// </remarks>
public void AbortTransaction()
{
_transactionCancelled = true;
if ((--_transactionDepth) == 0)
CleanupTransaction();
}
/// <summary>
/// Marks the current transaction scope as complete.
/// </summary>
public void CompleteTransaction()
{
if ((--_transactionDepth) == 0)
CleanupTransaction();
}
#endregion
#region Command Management
/// <summary>
/// Add a parameter to a DB command
/// </summary>
/// <param name="cmd">A reference to the IDbCommand to which the parameter is to be added</param>
/// <param name="value">The value to assign to the parameter</param>
/// <param name="pi">Optional, a reference to the property info of the POCO property from which the value is coming.</param>
void AddParam(IDbCommand cmd, object value, PropertyInfo pi)
{
// Convert value to from poco type to db type
if (pi != null)
{
var mapper = Mappers.GetMapper(pi.DeclaringType);
var fn = mapper.GetToDbConverter(pi);
if (fn != null)
value = fn(value);
}
// Support passed in parameters
var idbParam = value as IDbDataParameter;
if (idbParam != null)
{
idbParam.ParameterName = string.Format("{0}{1}", _paramPrefix, cmd.Parameters.Count);
cmd.Parameters.Add(idbParam);
return;
}
// Create the parameter
var p = cmd.CreateParameter();
p.ParameterName = string.Format("{0}{1}", _paramPrefix, cmd.Parameters.Count);
// Assign the parmeter value
if (value == null)
{
p.Value = DBNull.Value;
}
else
{
// Give the database type first crack at converting to DB required type
value = _dbType.MapParameterValue(value);
var t = value.GetType();
if (t.IsEnum) // PostgreSQL .NET driver wont cast enum to int
{
p.Value = (int)value;
}
else if (t == typeof(Guid))
{
p.Value = value.ToString();
p.DbType = DbType.String;
p.Size = 40;
}
else if (t == typeof(string))
{
// out of memory exception occurs if trying to save more than 4000 characters to SQL Server CE NText column. Set before attempting to set Size, or Size will always max out at 4000
if ((value as string).Length + 1 > 4000 && p.GetType().Name == "SqlCeParameter")
p.GetType().GetProperty("SqlDbType").SetValue(p, SqlDbType.NText, null);
p.Size = Math.Max((value as string).Length + 1, 4000); // Help query plan caching by using common size
p.Value = value;
}
else if (t == typeof(AnsiString))
{
// Thanks @DataChomp for pointing out the SQL Server indexing performance hit of using wrong string type on varchar
p.Size = Math.Max((value as AnsiString).Value.Length + 1, 4000);
p.Value = (value as AnsiString).Value;
p.DbType = DbType.AnsiString;
}
else if (value.GetType().Name == "SqlGeography") //SqlGeography is a CLR Type
{
p.GetType().GetProperty("UdtTypeName").SetValue(p, "geography", null); //geography is the equivalent SQL Server Type
p.Value = value;
}
else if (value.GetType().Name == "SqlGeometry") //SqlGeometry is a CLR Type
{
p.GetType().GetProperty("UdtTypeName").SetValue(p, "geometry", null); //geography is the equivalent SQL Server Type
p.Value = value;
}
else
{
p.Value = value;
}
}
// Add to the collection
cmd.Parameters.Add(p);
}
// Create a command
static Regex rxParamsPrefix = new Regex(@"(?<!@)@\w+", RegexOptions.Compiled);
public IDbCommand CreateCommand(IDbConnection connection, string sql, params object[] args)
{
// Perform named argument replacements
if (EnableNamedParams)
{
var new_args = new List<object>();
sql = ParametersHelper.ProcessParams(sql, args, new_args);
args = new_args.ToArray();
}
// Perform parameter prefix replacements
if (_paramPrefix != "@")
sql = rxParamsPrefix.Replace(sql, m => _paramPrefix + m.Value.Substring(1));
sql = sql.Replace("@@", "@"); // <- double @@ escapes a single @
// Create the command and add parameters
IDbCommand cmd = connection.CreateCommand();
cmd.Connection = connection;
cmd.CommandText = sql;
cmd.Transaction = _transaction;
foreach (var item in args)
{
AddParam(cmd, item, null);
}
// Notify the DB type
_dbType.PreExecute(cmd);
// Call logging
if (!String.IsNullOrEmpty(sql))
DoPreExecute(cmd);
return cmd;
}
#endregion
#region Exception Reporting and Logging
/// <summary>
/// Called if an exception occurs during processing of a DB operation. Override to provide custom logging/handling.
/// </summary>
/// <param name="x">The exception instance</param>
/// <returns>True to re-throw the exception, false to suppress it</returns>
public virtual bool OnException(Exception x)
{
System.Diagnostics.Debug.WriteLine(x.ToString());
System.Diagnostics.Debug.WriteLine(LastCommand);
return true;
}
/// <summary>
/// Called when DB connection opened
/// </summary>
/// <param name="conn">The newly opened IDbConnection</param>
/// <returns>The same or a replacement IDbConnection</returns>
/// <remarks>
/// Override this method to provide custom logging of opening connection, or
/// to provide a proxy IDbConnection.
/// </remarks>
public virtual IDbConnection OnConnectionOpened(IDbConnection conn)
{
return conn;
}
/// <summary>
/// Called when DB connection closed
/// </summary>
/// <param name="conn">The soon to be closed IDBConnection</param>
public virtual void OnConnectionClosing(IDbConnection conn)
{
}
/// <summary>
/// Called just before an DB command is executed
/// </summary>
/// <param name="cmd">The command to be executed</param>
/// <remarks>
/// Override this method to provide custom logging of commands and/or
/// modification of the IDbCommand before it's executed
/// </remarks>
public virtual void OnExecutingCommand(IDbCommand cmd)
{
}
/// <summary>
/// Called on completion of command execution
/// </summary>
/// <param name="cmd">The IDbCommand that finished executing</param>
public virtual void OnExecutedCommand(IDbCommand cmd)
{
}
#endregion
#region operation: Execute
/// <summary>
/// Executes a non-query command
/// </summary>
/// <param name="sql">The SQL statement to execute</param>
/// <param name="args">Arguments to any embedded parameters in the SQL</param>
/// <returns>The number of rows affected</returns>
public int Execute(string sql, params object[] args)
{
try
{
OpenSharedConnection();
try
{
using (var cmd = CreateCommand(_sharedConnection, sql, args))
{
var retv=cmd.ExecuteNonQuery();
OnExecutedCommand(cmd);
return retv;
}
}
finally
{
CloseSharedConnection();
}
}
catch (Exception x)
{
if (OnException(x))
throw;
return -1;
}
}
/// <summary>
/// Executes a non-query command
/// </summary>
/// <param name="sql">An SQL builder object representing the query and it's arguments</param>
/// <returns>The number of rows affected</returns>
public int Execute(Sql sql)
{
return Execute(sql.SQL, sql.Arguments);
}
#endregion
#region operation: ExecuteScalar
/// <summary>
/// Executes a query and return the first column of the first row in the result set.
/// </summary>
/// <typeparam name="T">The type that the result value should be cast to</typeparam>
/// <param name="sql">The SQL query to execute</param>
/// <param name="args">Arguments to any embedded parameters in the SQL</param>
/// <returns>The scalar value cast to T</returns>
public T ExecuteScalar<T>(string sql, params object[] args)
{
try
{
OpenSharedConnection();
try
{
using (var cmd = CreateCommand(_sharedConnection, sql, args))
{
object val = cmd.ExecuteScalar();
OnExecutedCommand(cmd);
// Handle nullable types
Type u = Nullable.GetUnderlyingType(typeof(T));
if (u != null && val == null)
return default(T);
return (T)Convert.ChangeType(val, u==null ? typeof(T) : u);
}
}
finally
{
CloseSharedConnection();
}
}
catch (Exception x)
{
if (OnException(x))
throw;
return default(T);
}
}
/// <summary>
/// Executes a query and return the first column of the first row in the result set.
/// </summary>
/// <typeparam name="T">The type that the result value should be cast to</typeparam>
/// <param name="sql">An SQL builder object representing the query and it's arguments</param>
/// <returns>The scalar value cast to T</returns>
public T ExecuteScalar<T>(Sql sql)
{
return ExecuteScalar<T>(sql.SQL, sql.Arguments);
}
#endregion
#region operation: Fetch
/// <summary>
/// Runs a query and returns the result set as a typed list
/// </summary>
/// <typeparam name="T">The Type representing a row in the result set</typeparam>
/// <param name="sql">The SQL query to execute</param>
/// <param name="args">Arguments to any embedded parameters in the SQL</param>
/// <returns>A List holding the results of the query</returns>
public List<T> Fetch<T>(string sql, params object[] args)
{
return Query<T>(sql, args).ToList();
}
/// <summary>
/// Runs a query and returns the result set as a typed list
/// </summary>
/// <typeparam name="T">The Type representing a row in the result set</typeparam>
/// <param name="sql">An SQL builder object representing the query and it's arguments</param>
/// <returns>A List holding the results of the query</returns>
public List<T> Fetch<T>(Sql sql)
{
return Fetch<T>(sql.SQL, sql.Arguments);
}
#endregion
#region operation: Page
/// <summary>
/// Starting with a regular SELECT statement, derives the SQL statements required to query a
/// DB for a page of records and the total number of records
/// </summary>
/// <typeparam name="T">The Type representing a row in the result set</typeparam>
/// <param name="skip">The number of rows to skip before the start of the page</param>
/// <param name="take">The number of rows in the page</param>
/// <param name="sql">The original SQL select statement</param>
/// <param name="args">Arguments to any embedded parameters in the SQL</param>
/// <param name="sqlCount">Outputs the SQL statement to query for the total number of matching rows</param>
/// <param name="sqlPage">Outputs the SQL statement to retrieve a single page of matching rows</param>
void BuildPageQueries<T>(long skip, long take, string sql, ref object[] args, out string sqlCount, out string sqlPage)
{
// Add auto select clause
if (EnableAutoSelect)
sql = AutoSelectHelper.AddSelectClause<T>(_dbType, sql);
// Split the SQL
PagingHelper.SQLParts parts;
if (!PagingHelper.SplitSQL(sql, out parts))
throw new Exception("Unable to parse SQL statement for paged query");
sqlPage = _dbType.BuildPageQuery(skip, take, parts, ref args);
sqlCount = parts.sqlCount;
}
/// <summary>
/// Retrieves a page of records and the total number of available records
/// </summary>
/// <typeparam name="T">The Type representing a row in the result set</typeparam>
/// <param name="page">The 1 based page number to retrieve</param>
/// <param name="itemsPerPage">The number of records per page</param>
/// <param name="sqlCount">The SQL to retrieve the total number of records</param>
/// <param name="countArgs">Arguments to any embedded parameters in the sqlCount statement</param>
/// <param name="sqlPage">The SQL To retrieve a single page of results</param>
/// <param name="pageArgs">Arguments to any embedded parameters in the sqlPage statement</param>
/// <returns>A Page of results</returns>
/// <remarks>
/// This method allows separate SQL statements to be explicitly provided for the two parts of the page query.
/// The page and itemsPerPage parameters are not used directly and are used simply to populate the returned Page object.
/// </remarks>
public Page<T> Page<T>(long page, long itemsPerPage, string sqlCount, object[] countArgs, string sqlPage, object[] pageArgs)
{
// Save the one-time command time out and use it for both queries
var saveTimeout = OneTimeCommandTimeout;
// Setup the paged result
var result = new Page<T>
{
CurrentPage = page,
ItemsPerPage = itemsPerPage,
TotalItems = ExecuteScalar<long>(sqlCount, countArgs)
};
result.TotalPages = result.TotalItems / itemsPerPage;
if ((result.TotalItems % itemsPerPage) != 0)
result.TotalPages++;
OneTimeCommandTimeout = saveTimeout;
// Get the records
result.Items = Fetch<T>(sqlPage, pageArgs);
// Done
return result;
}
/// <summary>
/// Retrieves a page of records and the total number of available records
/// </summary>
/// <typeparam name="T">The Type representing a row in the result set</typeparam>
/// <param name="page">The 1 based page number to retrieve</param>
/// <param name="itemsPerPage">The number of records per page</param>
/// <param name="sql">The base SQL query</param>
/// <param name="args">Arguments to any embedded parameters in the SQL statement</param>
/// <returns>A Page of results</returns>
/// <remarks>
/// PetaPoco will automatically modify the supplied SELECT statement to only retrieve the
/// records for the specified page. It will also execute a second query to retrieve the
/// total number of records in the result set.
/// </remarks>
public Page<T> Page<T>(long page, long itemsPerPage, string sql, params object[] args)
{
string sqlCount, sqlPage;
BuildPageQueries<T>((page-1)*itemsPerPage, itemsPerPage, sql, ref args, out sqlCount, out sqlPage);
return Page<T>(page, itemsPerPage, sqlCount, args, sqlPage, args);
}
/// <summary>
/// Retrieves a page of records and the total number of available records
/// </summary>
/// <typeparam name="T">The Type representing a row in the result set</typeparam>
/// <param name="page">The 1 based page number to retrieve</param>
/// <param name="itemsPerPage">The number of records per page</param>
/// <param name="sql">An SQL builder object representing the base SQL query and it's arguments</param>
/// <returns>A Page of results</returns>
/// <remarks>
/// PetaPoco will automatically modify the supplied SELECT statement to only retrieve the
/// records for the specified page. It will also execute a second query to retrieve the
/// total number of records in the result set.
/// </remarks>
public Page<T> Page<T>(long page, long itemsPerPage, Sql sql)
{
return Page<T>(page, itemsPerPage, sql.SQL, sql.Arguments);
}
/// <summary>
/// Retrieves a page of records and the total number of available records
/// </summary>
/// <typeparam name="T">The Type representing a row in the result set</typeparam>
/// <param name="page">The 1 based page number to retrieve</param>
/// <param name="itemsPerPage">The number of records per page</param>
/// <param name="sqlCount">An SQL builder object representing the SQL to retrieve the total number of records</param>
/// <param name="sqlPage">An SQL builder object representing the SQL to retrieve a single page of results</param>
/// <returns>A Page of results</returns>
/// <remarks>
/// This method allows separate SQL statements to be explicitly provided for the two parts of the page query.
/// The page and itemsPerPage parameters are not used directly and are used simply to populate the returned Page object.
/// </remarks>
public Page<T> Page<T>(long page, long itemsPerPage, Sql sqlCount, Sql sqlPage)
{
return Page<T>(page, itemsPerPage, sqlCount.SQL, sqlCount.Arguments, sqlPage.SQL, sqlPage.Arguments);
}
#endregion
#region operation: Fetch (page)
/// <summary>
/// Retrieves a page of records (without the total count)
/// </summary>
/// <typeparam name="T">The Type representing a row in the result set</typeparam>
/// <param name="page">The 1 based page number to retrieve</param>
/// <param name="itemsPerPage">The number of records per page</param>
/// <param name="sql">The base SQL query</param>
/// <param name="args">Arguments to any embedded parameters in the SQL statement</param>
/// <returns>A List of results</returns>
/// <remarks>
/// PetaPoco will automatically modify the supplied SELECT statement to only retrieve the
/// records for the specified page.
/// </remarks>
public List<T> Fetch<T>(long page, long itemsPerPage, string sql, params object[] args)
{
return SkipTake<T>((page - 1) * itemsPerPage, itemsPerPage, sql, args);
}
/// <summary>
/// Retrieves a page of records (without the total count)
/// </summary>
/// <typeparam name="T">The Type representing a row in the result set</typeparam>
/// <param name="page">The 1 based page number to retrieve</param>
/// <param name="itemsPerPage">The number of records per page</param>
/// <param name="sql">An SQL builder object representing the base SQL query and it's arguments</param>
/// <returns>A List of results</returns>
/// <remarks>
/// PetaPoco will automatically modify the supplied SELECT statement to only retrieve the
/// records for the specified page.
/// </remarks>
public List<T> Fetch<T>(long page, long itemsPerPage, Sql sql)
{
return SkipTake<T>((page - 1) * itemsPerPage, itemsPerPage, sql.SQL, sql.Arguments);
}
#endregion
#region operation: SkipTake
/// <summary>
/// Retrieves a range of records from result set
/// </summary>
/// <typeparam name="T">The Type representing a row in the result set</typeparam>
/// <param name="skip">The number of rows at the start of the result set to skip over</param>
/// <param name="take">The number of rows to retrieve</param>
/// <param name="sql">The base SQL query</param>
/// <param name="args">Arguments to any embedded parameters in the SQL statement</param>
/// <returns>A List of results</returns>
/// <remarks>
/// PetaPoco will automatically modify the supplied SELECT statement to only retrieve the
/// records for the specified range.
/// </remarks>
public List<T> SkipTake<T>(long skip, long take, string sql, params object[] args)
{
string sqlCount, sqlPage;
BuildPageQueries<T>(skip, take, sql, ref args, out sqlCount, out sqlPage);
return Fetch<T>(sqlPage, args);
}
/// <summary>
/// Retrieves a range of records from result set
/// </summary>
/// <typeparam name="T">The Type representing a row in the result set</typeparam>
/// <param name="skip">The number of rows at the start of the result set to skip over</param>
/// <param name="take">The number of rows to retrieve</param>
/// <param name="sql">An SQL builder object representing the base SQL query and it's arguments</param>
/// <returns>A List of results</returns>
/// <remarks>
/// PetaPoco will automatically modify the supplied SELECT statement to only retrieve the
/// records for the specified range.
/// </remarks>
public List<T> SkipTake<T>(long skip, long take, Sql sql)
{
return SkipTake<T>(skip, take, sql.SQL, sql.Arguments);
}
#endregion
#region operation: Query
/// <summary>
/// Runs an SQL query, returning the results as an IEnumerable collection
/// </summary>
/// <typeparam name="T">The Type representing a row in the result set</typeparam>
/// <param name="sql">The SQL query</param>
/// <param name="args">Arguments to any embedded parameters in the SQL statement</param>
/// <returns>An enumerable collection of result records</returns>
/// <remarks>
/// For some DB providers, care should be taken to not start a new Query before finishing with
/// and disposing the previous one. In cases where this is an issue, consider using Fetch which
/// returns the results as a List rather than an IEnumerable.
/// </remarks>
public IEnumerable<T> Query<T>(string sql, params object[] args)
{
if (EnableAutoSelect)
sql = AutoSelectHelper.AddSelectClause<T>(_dbType, sql);
OpenSharedConnection();
try
{
using (var cmd = CreateCommand(_sharedConnection, sql, args))
{
IDataReader r;
var pd = PocoData.ForType(typeof(T));
try
{
r = cmd.ExecuteReader();
OnExecutedCommand(cmd);
}
catch (Exception x)
{
if (OnException(x))
throw;
yield break;
}
var factory = pd.GetFactory(cmd.CommandText, _sharedConnection.ConnectionString, 0, r.FieldCount, r) as Func<IDataReader, T>;
using (r)
{
while (true)
{
T poco;
try
{
if (!r.Read())
yield break;
poco = factory(r);
}
catch (Exception x)
{
if (OnException(x))
throw;
yield break;
}
yield return poco;
}
}
}
}
finally
{
CloseSharedConnection();
}
}
/// <summary>
/// Runs an SQL query, returning the results as an IEnumerable collection
/// </summary>
/// <typeparam name="T">The Type representing a row in the result set</typeparam>
/// <param name="sql">An SQL builder object representing the base SQL query and it's arguments</param>
/// <returns>An enumerable collection of result records</returns>
/// <remarks>
/// For some DB providers, care should be taken to not start a new Query before finishing with
/// and disposing the previous one. In cases where this is an issue, consider using Fetch which
/// returns the results as a List rather than an IEnumerable.
/// </remarks>
public IEnumerable<T> Query<T>(Sql sql)
{
return Query<T>(sql.SQL, sql.Arguments);
}
#endregion
#region operation: Exists
/// <summary>
/// Checks for the existance of a row matching the specified condition
/// </summary>
/// <typeparam name="T">The Type representing the table being queried</typeparam>
/// <param name="sqlCondition">The SQL expression to be tested for (ie: the WHERE expression)</param>
/// <param name="args">Arguments to any embedded parameters in the SQL statement</param>
/// <returns>True if a record matching the condition is found.</returns>
public bool Exists<T>(string sqlCondition, params object[] args)
{
var poco = PocoData.ForType(typeof(T)).TableInfo;
return ExecuteScalar<int>(string.Format(_dbType.GetExistsSql(), poco.TableName, sqlCondition), args) != 0;
}
/// <summary>
/// Checks for the existance of a row with the specified primary key value.
/// </summary>
/// <typeparam name="T">The Type representing the table being queried</typeparam>
/// <param name="primaryKey">The primary key value to look for</param>
/// <returns>True if a record with the specified primary key value exists.</returns>
public bool Exists<T>(object primaryKey)
{
return Exists<T>(string.Format("{0}=@0", _dbType.EscapeSqlIdentifier(PocoData.ForType(typeof(T)).TableInfo.PrimaryKey)), primaryKey);
}
#endregion
#region operation: linq style (Exists, Single, SingleOrDefault etc...)
/// <summary>
/// Returns the record with the specified primary key value
/// </summary>
/// <typeparam name="T">The Type representing a row in the result set</typeparam>
/// <param name="primaryKey">The primary key value of the record to fetch</param>
/// <returns>The single record matching the specified primary key value</returns>
/// <remarks>
/// Throws an exception if there are zero or more than one record with the specified primary key value.
/// </remarks>
public T Single<T>(object primaryKey)
{
return Single<T>(string.Format("WHERE {0}=@0", _dbType.EscapeSqlIdentifier(PocoData.ForType(typeof(T)).TableInfo.PrimaryKey)), primaryKey);
}
/// <summary>
/// Returns the record with the specified primary key value, or the default value if not found
/// </summary>
/// <typeparam name="T">The Type representing a row in the result set</typeparam>
/// <param name="primaryKey">The primary key value of the record to fetch</param>
/// <returns>The single record matching the specified primary key value</returns>
/// <remarks>
/// If there are no records with the specified primary key value, default(T) (typically null) is returned.
/// </remarks>
public T SingleOrDefault<T>(object primaryKey)
{
return SingleOrDefault<T>(string.Format("WHERE {0}=@0", _dbType.EscapeSqlIdentifier(PocoData.ForType(typeof(T)).TableInfo.PrimaryKey)), primaryKey);
}
/// <summary>
/// Runs a query that should always return a single row.
/// </summary>
/// <typeparam name="T">The Type representing a row in the result set</typeparam>
/// <param name="sql">The SQL query</param>
/// <param name="args">Arguments to any embedded parameters in the SQL statement</param>
/// <returns>The single record matching the specified primary key value</returns>
/// <remarks>
/// Throws an exception if there are zero or more than one matching record
/// </remarks>
public T Single<T>(string sql, params object[] args)
{
return Query<T>(sql, args).Single();
}
/// <summary>
/// Runs a query that should always return either a single row, or no rows
/// </summary>
/// <typeparam name="T">The Type representing a row in the result set</typeparam>