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
1001
1002
|
// Copyright (c) .NET Foundation and contributors. All rights reserved. Licensed under the Microsoft Reciprocal License. See LICENSE.TXT file in the project root for full license information.
#include "precomp.h"
// okay, this may look a little weird, but sqlutil.h cannot be in the
// pre-compiled header because we need to #define these things so the
// correct GUID's get pulled into this object file
#include <initguid.h>
#define DBINITCONSTANTS
#include "sqlutil.h"
//Please note that only SQL native client 11 has TLS1.2 support
#define _SQLNCLI_OLEDB_DEPRECATE_WARNING
#if !defined(SQLNCLI_VER)
#define SQLNCLI_VER 1100
#endif
#if SQLNCLI_VER >= 1100
#if defined(_SQLNCLI_OLEDB_) || !defined(_SQLNCLI_ODBC_)
#define SQLNCLI_CLSID CLSID_SQLNCLI11
#endif // defined(_SQLNCLI_OLEDB_) || !defined(_SQLNCLI_ODBC_)
extern const GUID OLEDBDECLSPEC _SQLNCLI_OLEDB_DEPRECATE_WARNING CLSID_SQLNCLI11 = { 0x397C2819L,0x8272,0x4532,{ 0xAD,0x3A,0xFB,0x5E,0x43,0xBE,0xAA,0x39 } };
#endif // SQLNCLI_VER >= 1100
// Exit macros
#define SqlExitTrace(x, s, ...) ExitTraceSource(DUTIL_SOURCE_SQLUTIL, x, s, __VA_ARGS__)
#define SqlExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_SQLUTIL, x, s, __VA_ARGS__)
#define SqlExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_SQLUTIL, x, s, __VA_ARGS__)
#define SqlExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_SQLUTIL, x, s, __VA_ARGS__)
#define SqlExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_SQLUTIL, x, s, __VA_ARGS__)
#define SqlExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_SQLUTIL, x, s, __VA_ARGS__)
#define SqlExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_SQLUTIL, x, s, __VA_ARGS__)
#define SqlExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_SQLUTIL, p, x, e, s, __VA_ARGS__)
#define SqlExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_SQLUTIL, p, x, s, __VA_ARGS__)
#define SqlExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_SQLUTIL, p, x, e, s, __VA_ARGS__)
#define SqlExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_SQLUTIL, p, x, s, __VA_ARGS__)
#define SqlExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_SQLUTIL, e, x, s, __VA_ARGS__)
#define SqlExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_SQLUTIL, g, x, s, __VA_ARGS__)
// private prototypes
static HRESULT InitializeDatabaseConnection(
__in REFCLSID rclsid,
__in_z LPCSTR szFriendlyClsidName,
__in DBPROPSET rgdbpsetInit[],
__in_ecount(rgdbpsetInit) DWORD cdbpsetInit,
__out IDBCreateSession** ppidbSession
);
HRESULT DumpErrorRecords();
static HRESULT FileSpecToString(
__in const SQL_FILESPEC* psf,
__out LPWSTR* ppwz
);
static HRESULT EscapeSqlIdentifier(
__in_z LPCWSTR wzDatabase,
__deref_out_z LPWSTR* ppwz
);
/********************************************************************
SqlConnectDatabase - establishes a connection to a database
NOTE: wzInstance is optional
if fIntegratedAuth is set then wzUser and wzPassword are ignored
********************************************************************/
extern "C" HRESULT DAPI SqlConnectDatabase(
__in_z LPCWSTR wzServer,
__in_z LPCWSTR wzInstance,
__in_z LPCWSTR wzDatabase,
__in BOOL fIntegratedAuth,
__in_z LPCWSTR wzUser,
__in_z LPCWSTR wzPassword,
__out IDBCreateSession** ppidbSession
)
{
Assert(wzServer && wzDatabase && *wzDatabase && ppidbSession);
HRESULT hr = S_OK;
LPWSTR pwzServerInstance = NULL;
DBPROP rgdbpInit[4] = { };
DBPROPSET rgdbpsetInit[1] = { };
ULONG cProperties = 0;
// if there is an instance
if (wzInstance && *wzInstance)
{
hr = StrAllocFormatted(&pwzServerInstance, L"%s\\%s", wzServer, wzInstance);
}
else
{
hr = StrAllocString(&pwzServerInstance, wzServer, 0);
}
SqlExitOnFailure(hr, "failed to allocate memory for the server instance");
// server[\instance]
rgdbpInit[cProperties].dwPropertyID = DBPROP_INIT_DATASOURCE;
rgdbpInit[cProperties].dwOptions = DBPROPOPTIONS_REQUIRED;
rgdbpInit[cProperties].colid = DB_NULLID;
::VariantInit(&rgdbpInit[cProperties].vValue);
rgdbpInit[cProperties].vValue.vt = VT_BSTR;
rgdbpInit[cProperties].vValue.bstrVal = ::SysAllocString(pwzServerInstance);
++cProperties;
// database
rgdbpInit[cProperties].dwPropertyID = DBPROP_INIT_CATALOG;
rgdbpInit[cProperties].dwOptions = DBPROPOPTIONS_REQUIRED;
rgdbpInit[cProperties].colid = DB_NULLID;
::VariantInit(&rgdbpInit[cProperties].vValue);
rgdbpInit[cProperties].vValue.vt = VT_BSTR;
rgdbpInit[cProperties].vValue.bstrVal= ::SysAllocString(wzDatabase);
++cProperties;
if (fIntegratedAuth)
{
// username
rgdbpInit[cProperties].dwPropertyID = DBPROP_AUTH_INTEGRATED;
rgdbpInit[cProperties].dwOptions = DBPROPOPTIONS_REQUIRED;
rgdbpInit[cProperties].colid = DB_NULLID;
::VariantInit(&rgdbpInit[cProperties].vValue);
rgdbpInit[cProperties].vValue.vt = VT_BSTR;
rgdbpInit[cProperties].vValue.bstrVal = ::SysAllocString(L"SSPI"); // default windows authentication
++cProperties;
}
else
{
// username
rgdbpInit[cProperties].dwPropertyID = DBPROP_AUTH_USERID;
rgdbpInit[cProperties].dwOptions = DBPROPOPTIONS_REQUIRED;
rgdbpInit[cProperties].colid = DB_NULLID;
::VariantInit(&rgdbpInit[cProperties].vValue);
rgdbpInit[cProperties].vValue.vt = VT_BSTR;
rgdbpInit[cProperties].vValue.bstrVal = ::SysAllocString(wzUser);
++cProperties;
// password
rgdbpInit[cProperties].dwPropertyID = DBPROP_AUTH_PASSWORD;
rgdbpInit[cProperties].dwOptions = DBPROPOPTIONS_REQUIRED;
rgdbpInit[cProperties].colid = DB_NULLID;
::VariantInit(&rgdbpInit[cProperties].vValue);
rgdbpInit[cProperties].vValue.vt = VT_BSTR;
rgdbpInit[cProperties].vValue.bstrVal = ::SysAllocString(wzPassword);
++cProperties;
}
// put the properties into a set
rgdbpsetInit[0].guidPropertySet = DBPROPSET_DBINIT;
rgdbpsetInit[0].rgProperties = rgdbpInit;
rgdbpsetInit[0].cProperties = cProperties;
// obtain access to the SQL Native Client provider
hr = InitializeDatabaseConnection(SQLNCLI_CLSID, "SQL Native Client", rgdbpsetInit, countof(rgdbpsetInit), ppidbSession);
if (FAILED(hr))
{
SqlExitTrace(hr, "Could not initialize SQL Native Client, falling back to SQL OLE DB...");
// try OLE DB but if that fails return original error failure
HRESULT hr2 = InitializeDatabaseConnection(CLSID_SQLOLEDB, "SQL OLE DB", rgdbpsetInit, countof(rgdbpsetInit), ppidbSession);
if (FAILED(hr2))
{
SqlExitTrace(hr2, "Could not initialize SQL OLE DB either, giving up.");
}
else
{
hr = S_OK;
}
}
LExit:
for (; 0 < cProperties; cProperties--)
{
::VariantClear(&rgdbpInit[cProperties - 1].vValue);
}
ReleaseStr(pwzServerInstance);
return hr;
}
/********************************************************************
SqlStartTransaction - Starts a new transaction that must be ended
*********************************************************************/
extern "C" HRESULT DAPI SqlStartTransaction(
__in IDBCreateSession* pidbSession,
__out IDBCreateCommand** ppidbCommand,
__out ITransaction** ppit
)
{
Assert(pidbSession && ppit);
HRESULT hr = S_OK;
hr = pidbSession->CreateSession(NULL, IID_IDBCreateCommand, (IUnknown**)ppidbCommand);
SqlExitOnFailure(hr, "unable to create command from session");
hr = (*ppidbCommand)->QueryInterface(IID_ITransactionLocal, (LPVOID*)ppit);
SqlExitOnFailure(hr, "Unable to QueryInterface session to get ITransactionLocal");
hr = ((ITransactionLocal*)*ppit)->StartTransaction(ISOLATIONLEVEL_SERIALIZABLE, 0, NULL, NULL);
LExit:
return hr;
}
/********************************************************************
SqlEndTransaction - Ends the transaction
NOTE: if fCommit, will commit the transaction, otherwise rolls back
*********************************************************************/
extern "C" HRESULT DAPI SqlEndTransaction(
__in ITransaction* pit,
__in BOOL fCommit
)
{
Assert(pit);
HRESULT hr = S_OK;
if (fCommit)
{
hr = pit->Commit(FALSE, XACTTC_SYNC, 0);
SqlExitOnFailure(hr, "commit of transaction failed");
}
else
{
hr = pit->Abort(NULL, FALSE, FALSE);
SqlExitOnFailure(hr, "abort of transaction failed");
}
LExit:
return hr;
}
/********************************************************************
SqlDatabaseExists - determines if database exists
NOTE: wzInstance is optional
if fIntegratedAuth is set then wzUser and wzPassword are ignored
returns S_OK if database exist
returns S_FALSE if database does not exist
returns E_* on error
********************************************************************/
extern "C" HRESULT DAPI SqlDatabaseExists(
__in_z LPCWSTR wzServer,
__in_z LPCWSTR wzInstance,
__in_z LPCWSTR wzDatabase,
__in BOOL fIntegratedAuth,
__in_z LPCWSTR wzUser,
__in_z LPCWSTR wzPassword,
__out_opt BSTR* pbstrErrorDescription
)
{
Assert(wzServer && wzDatabase && *wzDatabase);
HRESULT hr = S_OK;
IDBCreateSession* pidbSession = NULL;
hr = SqlConnectDatabase(wzServer, wzInstance, L"master", fIntegratedAuth, wzUser, wzPassword, &pidbSession);
SqlExitOnFailure(hr, "failed to connect to 'master' database on server %ls", wzServer);
hr = SqlSessionDatabaseExists(pidbSession, wzDatabase, pbstrErrorDescription);
LExit:
ReleaseObject(pidbSession);
return hr;
}
/********************************************************************
SqlSessionDatabaseExists - determines if database exists
NOTE: pidbSession must be connected to master database
returns S_OK if database exist
returns S_FALSE if database does not exist
returns E_* on error
********************************************************************/
extern "C" HRESULT DAPI SqlSessionDatabaseExists(
__in IDBCreateSession* pidbSession,
__in_z LPCWSTR wzDatabase,
__out_opt BSTR* pbstrErrorDescription
)
{
Assert(pidbSession && wzDatabase && *wzDatabase);
HRESULT hr = S_OK;
LPWSTR pwzQuery = NULL;
IRowset* pirs = NULL;
DBCOUNTITEM cRows = 0;
HROW rghRows[1];
HROW* prow = rghRows;
//
// query to see if the database exists
//
hr = StrAllocFormatted(&pwzQuery, L"SELECT name FROM sysdatabases WHERE name='%s'", wzDatabase);
SqlExitOnFailure(hr, "failed to allocate query string to ensure database exists");
hr = SqlSessionExecuteQuery(pidbSession, pwzQuery, &pirs, NULL, pbstrErrorDescription);
SqlExitOnFailure(hr, "failed to get database list from 'master' database");
Assert(pirs);
//
// check to see if the database was returned
//
hr = pirs->GetNextRows(DB_NULL_HCHAPTER, 0, 1, &cRows, &prow);
SqlExitOnFailure(hr, "failed to get row with database name");
// succeeded but no database
if ((DB_S_ENDOFROWSET == hr) || (0 == cRows))
{
hr = S_FALSE;
}
LExit:
ReleaseObject(pirs);
ReleaseStr(pwzQuery);
return hr;
}
/********************************************************************
SqlDatabaseEnsureExists - creates a database if it does not exist
NOTE: wzInstance is optional
if fIntegratedAuth is set then wzUser and wzPassword are ignored
********************************************************************/
extern "C" HRESULT DAPI SqlDatabaseEnsureExists(
__in_z LPCWSTR wzServer,
__in_z LPCWSTR wzInstance,
__in_z LPCWSTR wzDatabase,
__in BOOL fIntegratedAuth,
__in_z LPCWSTR wzUser,
__in_z LPCWSTR wzPassword,
__in_opt const SQL_FILESPEC* psfDatabase,
__in_opt const SQL_FILESPEC* psfLog,
__out_opt BSTR* pbstrErrorDescription
)
{
Assert(wzServer && wzDatabase && *wzDatabase);
HRESULT hr = S_OK;
IDBCreateSession* pidbSession = NULL;
//
// connect to the master database to create the new database
//
hr = SqlConnectDatabase(wzServer, wzInstance, L"master", fIntegratedAuth, wzUser, wzPassword, &pidbSession);
SqlExitOnFailure(hr, "failed to connect to 'master' database on server %ls", wzServer);
hr = SqlSessionDatabaseEnsureExists(pidbSession, wzDatabase, psfDatabase, psfLog, pbstrErrorDescription);
SqlExitOnFailure(hr, "failed to create database: %ls", wzDatabase);
Assert(S_OK == hr);
LExit:
ReleaseObject(pidbSession);
return hr;
}
/********************************************************************
SqlSessionDatabaseEnsureExists - creates a database if it does not exist
NOTE: pidbSession must be connected to the master database
********************************************************************/
extern "C" HRESULT DAPI SqlSessionDatabaseEnsureExists(
__in IDBCreateSession* pidbSession,
__in_z LPCWSTR wzDatabase,
__in_opt const SQL_FILESPEC* psfDatabase,
__in_opt const SQL_FILESPEC* psfLog,
__out_opt BSTR* pbstrErrorDescription
)
{
Assert(pidbSession && wzDatabase && *wzDatabase);
HRESULT hr = S_OK;
hr = SqlSessionDatabaseExists(pidbSession, wzDatabase, pbstrErrorDescription);
SqlExitOnFailure(hr, "failed to determine if exists, database: %ls", wzDatabase);
if (S_FALSE == hr)
{
hr = SqlSessionCreateDatabase(pidbSession, wzDatabase, psfDatabase, psfLog, pbstrErrorDescription);
SqlExitOnFailure(hr, "failed to create database: %ls", wzDatabase);
}
// else database already exists, return S_FALSE
Assert(S_OK == hr);
LExit:
return hr;
}
/********************************************************************
SqlCreateDatabase - creates a database on the server
NOTE: wzInstance is optional
if fIntegratedAuth is set then wzUser and wzPassword are ignored
********************************************************************/
extern "C" HRESULT DAPI SqlCreateDatabase(
__in_z LPCWSTR wzServer,
__in_z LPCWSTR wzInstance,
__in_z LPCWSTR wzDatabase,
__in BOOL fIntegratedAuth,
__in_z LPCWSTR wzUser,
__in_z LPCWSTR wzPassword,
__in_opt const SQL_FILESPEC* psfDatabase,
__in_opt const SQL_FILESPEC* psfLog,
__out_opt BSTR* pbstrErrorDescription
)
{
Assert(wzServer && wzDatabase && *wzDatabase);
HRESULT hr = S_OK;
IDBCreateSession* pidbSession = NULL;
//
// connect to the master database to create the new database
//
hr = SqlConnectDatabase(wzServer, wzInstance, L"master", fIntegratedAuth, wzUser, wzPassword, &pidbSession);
SqlExitOnFailure(hr, "failed to connect to 'master' database on server %ls", wzServer);
hr = SqlSessionCreateDatabase(pidbSession, wzDatabase, psfDatabase, psfLog, pbstrErrorDescription);
SqlExitOnFailure(hr, "failed to create database: %ls", wzDatabase);
Assert(S_OK == hr);
LExit:
ReleaseObject(pidbSession);
return hr;
}
/********************************************************************
SqlSessionCreateDatabase - creates a database on the server
NOTE: pidbSession must be connected to the master database
********************************************************************/
extern "C" HRESULT DAPI SqlSessionCreateDatabase(
__in IDBCreateSession* pidbSession,
__in_z LPCWSTR wzDatabase,
__in_opt const SQL_FILESPEC* psfDatabase,
__in_opt const SQL_FILESPEC* psfLog,
__out_opt BSTR* pbstrErrorDescription
)
{
HRESULT hr = S_OK;
LPWSTR pwzDbFile = NULL;
LPWSTR pwzLogFile = NULL;
LPWSTR pwzQuery = NULL;
LPWSTR pwzDatabaseEscaped = NULL;
if (psfDatabase)
{
hr = FileSpecToString(psfDatabase, &pwzDbFile);
SqlExitOnFailure(hr, "failed to convert db filespec to string");
}
if (psfLog)
{
hr = FileSpecToString(psfLog, &pwzLogFile);
SqlExitOnFailure(hr, "failed to convert log filespec to string");
}
hr = EscapeSqlIdentifier(wzDatabase, &pwzDatabaseEscaped);
SqlExitOnFailure(hr, "failed to escape database string");
hr = StrAllocFormatted(&pwzQuery, L"CREATE DATABASE %s %s%s %s%s", pwzDatabaseEscaped, pwzDbFile ? L"ON " : L"", pwzDbFile ? pwzDbFile : L"", pwzLogFile ? L"LOG ON " : L"", pwzLogFile ? pwzLogFile : L"");
SqlExitOnFailure(hr, "failed to allocate query to create database: %ls", pwzDatabaseEscaped);
hr = SqlSessionExecuteQuery(pidbSession, pwzQuery, NULL, NULL, pbstrErrorDescription);
SqlExitOnFailure(hr, "failed to create database: %ls, Query: %ls", pwzDatabaseEscaped, pwzQuery);
LExit:
ReleaseStr(pwzQuery);
ReleaseStr(pwzLogFile);
ReleaseStr(pwzDbFile);
ReleaseStr(pwzDatabaseEscaped);
return hr;
}
/********************************************************************
SqlDropDatabase - removes a database from a server if it exists
NOTE: wzInstance is optional
if fIntegratedAuth is set then wzUser and wzPassword are ignored
********************************************************************/
extern "C" HRESULT DAPI SqlDropDatabase(
__in_z LPCWSTR wzServer,
__in_z LPCWSTR wzInstance,
__in_z LPCWSTR wzDatabase,
__in BOOL fIntegratedAuth,
__in_z LPCWSTR wzUser,
__in_z LPCWSTR wzPassword,
__out_opt BSTR* pbstrErrorDescription
)
{
Assert(wzServer && wzDatabase && *wzDatabase);
HRESULT hr = S_OK;
IDBCreateSession* pidbSession = NULL;
//
// connect to the master database to search for wzDatabase
//
hr = SqlConnectDatabase(wzServer, wzInstance, L"master", fIntegratedAuth, wzUser, wzPassword, &pidbSession);
SqlExitOnFailure(hr, "Failed to connect to 'master' database");
hr = SqlSessionDropDatabase(pidbSession, wzDatabase, pbstrErrorDescription);
LExit:
ReleaseObject(pidbSession);
return hr;
}
/********************************************************************
SqlSessionDropDatabase - removes a database from a server if it exists
NOTE: pidbSession must be connected to the master database
********************************************************************/
extern "C" HRESULT DAPI SqlSessionDropDatabase(
__in IDBCreateSession* pidbSession,
__in_z LPCWSTR wzDatabase,
__out_opt BSTR* pbstrErrorDescription
)
{
Assert(pidbSession && wzDatabase && *wzDatabase);
HRESULT hr = S_OK;
LPWSTR pwzQuery = NULL;
LPWSTR pwzDatabaseEscaped = NULL;
hr = SqlSessionDatabaseExists(pidbSession, wzDatabase, pbstrErrorDescription);
SqlExitOnFailure(hr, "failed to determine if exists, database: %ls", wzDatabase);
hr = EscapeSqlIdentifier(wzDatabase, &pwzDatabaseEscaped);
SqlExitOnFailure(hr, "failed to escape database string");
if (S_OK == hr)
{
hr = StrAllocFormatted(&pwzQuery, L"DROP DATABASE %s", pwzDatabaseEscaped);
SqlExitOnFailure(hr, "failed to allocate query to drop database: %ls", pwzDatabaseEscaped);
hr = SqlSessionExecuteQuery(pidbSession, pwzQuery, NULL, NULL, pbstrErrorDescription);
SqlExitOnFailure(hr, "Failed to drop database");
}
LExit:
ReleaseStr(pwzQuery);
ReleaseStr(pwzDatabaseEscaped);
return hr;
}
/********************************************************************
SqlSessionExecuteQuery - executes a query and returns the results if desired
NOTE: ppirs and pcRoes and pbstrErrorDescription are optional
********************************************************************/
extern "C" HRESULT DAPI SqlSessionExecuteQuery(
__in IDBCreateSession* pidbSession,
__in __sql_command LPCWSTR wzSql,
__out_opt IRowset** ppirs,
__out_opt DBROWCOUNT* pcRows,
__out_opt BSTR* pbstrErrorDescription
)
{
Assert(pidbSession);
HRESULT hr = S_OK;
IDBCreateCommand* pidbCommand = NULL;
ICommandText* picmdText = NULL;
ICommand* picmd = NULL;
DBROWCOUNT cRows = 0;
if (pcRows)
{
*pcRows = NULL;
}
//
// create the command
//
hr = pidbSession->CreateSession(NULL, IID_IDBCreateCommand, (IUnknown**)&pidbCommand);
SqlExitOnFailure(hr, "failed to create database session");
hr = pidbCommand->CreateCommand(NULL, IID_ICommand, (IUnknown**)&picmd);
SqlExitOnFailure(hr, "failed to create command to execute session");
//
// set the sql text into the command
//
hr = picmd->QueryInterface(IID_ICommandText, (LPVOID*)&picmdText);
SqlExitOnFailure(hr, "failed to get command text object for command");
hr = picmdText->SetCommandText(DBGUID_DEFAULT , wzSql);
SqlExitOnFailure(hr, "failed to set SQL string: %ls", wzSql);
//
// execute the command
//
hr = picmd->Execute(NULL, (ppirs) ? IID_IRowset : IID_NULL, NULL, &cRows, reinterpret_cast<IUnknown**>(ppirs));
SqlExitOnFailure(hr, "failed to execute SQL string: %ls", wzSql);
if (DB_S_ERRORSOCCURRED == hr)
{
hr = E_FAIL;
}
if (pcRows)
{
*pcRows = cRows;
}
LExit:
if (FAILED(hr) && picmd && pbstrErrorDescription)
{
HRESULT hrGetErrors = SqlGetErrorInfo(picmd, IID_ICommandText, 0x409, NULL, pbstrErrorDescription); // TODO: use current locale instead of always American-English
if (FAILED(hrGetErrors))
{
ReleaseBSTR(*pbstrErrorDescription);
}
}
ReleaseObject(picmd);
ReleaseObject(picmdText);
ReleaseObject(pidbCommand);
return hr;
}
/********************************************************************
SqlCommandExecuteQuery - executes a SQL command and returns the results if desired
NOTE: ppirs and pcRoes are optional
********************************************************************/
extern "C" HRESULT DAPI SqlCommandExecuteQuery(
__in IDBCreateCommand* pidbCommand,
__in __sql_command LPCWSTR wzSql,
__out IRowset** ppirs,
__out DBROWCOUNT* pcRows
)
{
Assert(pidbCommand);
HRESULT hr = S_OK;
ICommandText* picmdText = NULL;
ICommand* picmd = NULL;
DBROWCOUNT cRows = 0;
if (pcRows)
{
*pcRows = NULL;
}
//
// create the command
//
hr = pidbCommand->CreateCommand(NULL, IID_ICommand, (IUnknown**)&picmd);
SqlExitOnFailure(hr, "failed to create command to execute session");
//
// set the sql text into the command
//
hr = picmd->QueryInterface(IID_ICommandText, (LPVOID*)&picmdText);
SqlExitOnFailure(hr, "failed to get command text object for command");
hr = picmdText->SetCommandText(DBGUID_DEFAULT , wzSql);
SqlExitOnFailure(hr, "failed to set SQL string: %ls", wzSql);
//
// execute the command
//
hr = picmd->Execute(NULL, (ppirs) ? IID_IRowset : IID_NULL, NULL, &cRows, reinterpret_cast<IUnknown**>(ppirs));
SqlExitOnFailure(hr, "failed to execute SQL string: %ls", wzSql);
if (DB_S_ERRORSOCCURRED == hr)
{
hr = E_FAIL;
}
if (pcRows)
{
*pcRows = cRows;
}
LExit:
ReleaseObject(picmd);
ReleaseObject(picmdText);
return hr;
}
/********************************************************************
SqlGetErrorInfo - gets error information from the last SQL function call
NOTE: pbstrErrorSource and pbstrErrorDescription are optional
********************************************************************/
extern "C" HRESULT DAPI SqlGetErrorInfo(
__in IUnknown* pObjectWithError,
__in REFIID IID_InterfaceWithError,
__in DWORD dwLocaleId,
__out_opt BSTR* pbstrErrorSource,
__out_opt BSTR* pbstrErrorDescription
)
{
HRESULT hr = S_OK;
Assert(pObjectWithError);
// interfaces needed to extract error information out
ISupportErrorInfo* pISupportErrorInfo = NULL;
IErrorInfo* pIErrorInfoAll = NULL;
IErrorRecords* pIErrorRecords = NULL;
IErrorInfo* pIErrorInfoRecord = NULL;
// only ask for error information if the interface supports it.
hr = pObjectWithError->QueryInterface(IID_ISupportErrorInfo,(void**)&pISupportErrorInfo);
SqlExitOnFailure(hr, "No error information was found for object.");
hr = pISupportErrorInfo->InterfaceSupportsErrorInfo(IID_InterfaceWithError);
SqlExitOnFailure(hr, "InterfaceWithError is not supported for object with error");
// ignore the return of GetErrorInfo it can succeed and return a NULL pointer in pIErrorInfoAll anyway
hr = ::GetErrorInfo(0, &pIErrorInfoAll);
SqlExitOnFailure(hr, "failed to get error info");
if (S_OK == hr && pIErrorInfoAll)
{
// see if it's a valid OLE DB IErrorInfo interface that exposes a list of records
hr = pIErrorInfoAll->QueryInterface(IID_IErrorRecords, (void**)&pIErrorRecords);
if (SUCCEEDED(hr))
{
ULONG cErrors = 0;
pIErrorRecords->GetRecordCount(&cErrors);
// get the error information for each record
for (ULONG i = 0; i < cErrors; ++i)
{
hr = pIErrorRecords->GetErrorInfo(i, dwLocaleId, &pIErrorInfoRecord);
if (SUCCEEDED(hr))
{
if (pbstrErrorSource)
{
pIErrorInfoRecord->GetSource(pbstrErrorSource);
}
if (pbstrErrorDescription)
{
pIErrorInfoRecord->GetDescription(pbstrErrorDescription);
}
ReleaseNullObject(pIErrorInfoRecord);
break; // TODO: return more than one error in the future!
}
}
ReleaseNullObject(pIErrorRecords);
}
else // we have a simple error record
{
if (pbstrErrorSource)
{
pIErrorInfoAll->GetSource(pbstrErrorSource);
}
if (pbstrErrorDescription)
{
pIErrorInfoAll->GetDescription(pbstrErrorDescription);
}
}
}
else
{
hr = E_NOMOREITEMS;
}
LExit:
ReleaseObject(pIErrorInfoRecord);
ReleaseObject(pIErrorRecords);
ReleaseObject(pIErrorInfoAll);
ReleaseObject(pISupportErrorInfo);
return hr;
}
//
// private
//
static HRESULT InitializeDatabaseConnection(
__in REFCLSID rclsid,
__in_z LPCSTR szFriendlyClsidName,
__in DBPROPSET rgdbpsetInit[],
__in_ecount(rgdbpsetInit) DWORD cdbpsetInit,
__out IDBCreateSession** ppidbSession
)
{
Unused(szFriendlyClsidName); // only used in DEBUG builds
HRESULT hr = S_OK;
IDBInitialize* pidbInitialize = NULL;
IDBProperties* pidbProperties = NULL;
hr = ::CoCreateInstance(rclsid, NULL, CLSCTX_INPROC_SERVER, IID_IDBInitialize, (LPVOID*)&pidbInitialize);
SqlExitOnFailure(hr, "failed to initialize %s", szFriendlyClsidName);
// create and set the property set
hr = pidbInitialize->QueryInterface(IID_IDBProperties, (LPVOID*)&pidbProperties);
SqlExitOnFailure(hr, "failed to get IID_IDBProperties for %s", szFriendlyClsidName);
hr = pidbProperties->SetProperties(cdbpsetInit, rgdbpsetInit);
SqlExitOnFailure(hr, "failed to set properties for %s", szFriendlyClsidName);
// initialize connection to datasource
hr = pidbInitialize->Initialize();
if (FAILED(hr))
{
DumpErrorRecords();
}
SqlExitOnFailure(hr, "failed to initialize connection for %s", szFriendlyClsidName);
hr = pidbInitialize->QueryInterface(IID_IDBCreateSession, (LPVOID*)ppidbSession);
SqlExitOnFailure(hr, "failed to query for connection session for %s", szFriendlyClsidName);
LExit:
ReleaseObject(pidbProperties);
ReleaseObject(pidbInitialize);
return hr;
}
HRESULT DumpErrorRecords()
{
HRESULT hr = S_OK;
IErrorInfo* pIErrorInfo = NULL;
IErrorRecords* pIErrorRecords = NULL;
IErrorInfo* pIErrorInfoRecord = NULL;
BSTR bstrDescription = NULL;
ULONG i = 0;
ULONG cRecords = 0;
ERRORINFO ErrorInfo = { };
// Get IErrorInfo pointer from OLE.
hr = ::GetErrorInfo(0, &pIErrorInfo);
if (FAILED(hr))
{
ExitFunction();
}
// QI for IID_IErrorRecords.
hr = pIErrorInfo->QueryInterface(IID_IErrorRecords, (void**)&pIErrorRecords);
if (FAILED(hr))
{
ExitFunction();
}
// Get error record count.
hr = pIErrorRecords->GetRecordCount(&cRecords);
if (FAILED(hr))
{
ExitFunction();
}
// Loop through the error records.
for (i = 0; i < cRecords; i++)
{
// Get pIErrorInfo from pIErrorRecords.
hr = pIErrorRecords->GetErrorInfo(i, 1033, &pIErrorInfoRecord);
if (SUCCEEDED(hr))
{
// Get error description and source.
hr = pIErrorInfoRecord->GetDescription(&bstrDescription);
// Retrieve the ErrorInfo structures.
hr = pIErrorRecords->GetBasicErrorInfo(i, &ErrorInfo);
SqlExitTrace(ErrorInfo.hrError, "SQL error %lu/%lu: %ls", i + 1, cRecords, bstrDescription);
ReleaseNullObject(pIErrorInfoRecord);
ReleaseNullBSTR(bstrDescription);
}
}
LExit:
ReleaseNullBSTR(bstrDescription);
ReleaseObject(pIErrorInfoRecord);
ReleaseObject(pIErrorRecords);
ReleaseObject(pIErrorInfo);
return hr;
}
/********************************************************************
FileSpecToString
*********************************************************************/
static HRESULT FileSpecToString(
__in const SQL_FILESPEC* psf,
__out LPWSTR* ppwz
)
{
Assert(psf && ppwz);
HRESULT hr = S_OK;
LPWSTR pwz = NULL;
hr = StrAllocString(&pwz, L"(", 1024);
SqlExitOnFailure(hr, "failed to allocate string for database file info");
SqlExitOnNull(*psf->wzName, hr, E_INVALIDARG, "logical name not specified in database file info");
SqlExitOnNull(*psf->wzFilename, hr, E_INVALIDARG, "filename not specified in database file info");
hr = StrAllocFormatted(&pwz, L"%sNAME=%s", pwz, psf->wzName);
SqlExitOnFailure(hr, "failed to format database file info name: %ls", psf->wzName);
hr = StrAllocFormatted(&pwz, L"%s, FILENAME='%s'", pwz, psf->wzFilename);
SqlExitOnFailure(hr, "failed to format database file info filename: %ls", psf->wzFilename);
if (0 != psf->wzSize[0])
{
hr = StrAllocFormatted(&pwz, L"%s, SIZE=%s", pwz, psf->wzSize);
SqlExitOnFailure(hr, "failed to format database file info size: %ls", psf->wzSize);
}
if (0 != psf->wzMaxSize[0])
{
hr = StrAllocFormatted(&pwz, L"%s, MAXSIZE=%s", pwz, psf->wzMaxSize);
SqlExitOnFailure(hr, "failed to format database file info maxsize: %ls", psf->wzMaxSize);
}
if (0 != psf->wzGrow[0])
{
hr = StrAllocFormatted(&pwz, L"%s, FILEGROWTH=%s", pwz, psf->wzGrow);
SqlExitOnFailure(hr, "failed to format database file info growth: %ls", psf->wzGrow);
}
hr = StrAllocFormatted(&pwz, L"%s)", pwz);
SqlExitOnFailure(hr, "failed to allocate string for file spec");
*ppwz = pwz;
pwz = NULL; // null here so it doesn't get freed below
LExit:
ReleaseStr(pwz);
return hr;
}
static HRESULT EscapeSqlIdentifier(
__in_z LPCWSTR wzIdentifier,
__deref_out_z LPWSTR* ppwz
)
{
Assert(ppwz);
HRESULT hr = S_OK;
LPWSTR pwz = NULL;
if (wzIdentifier == NULL)
{
//Just ignore a NULL identifier and clear out the result
ReleaseNullStr(*ppwz);
ExitFunction();
}
int cchIdentifier = lstrlenW(wzIdentifier);
//If an empty string or already escaped just copy
if (cchIdentifier == 0 || (wzIdentifier[0] == '[' && wzIdentifier[cchIdentifier-1] == ']'))
{
hr = StrAllocString(&pwz, wzIdentifier, 0);
SqlExitOnFailure(hr, "failed to format database name: %ls", wzIdentifier);
}
else
{
//escape it
hr = StrAllocFormatted(&pwz, L"[%s]", wzIdentifier);
SqlExitOnFailure(hr, "failed to format escaped database name: %ls", wzIdentifier);
}
*ppwz = pwz;
pwz = NULL; // null here so it doesn't get freed below
LExit:
ReleaseStr(pwz);
return hr;
}
|