forked from MapServer/MapServer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mapmssql2008.c
2267 lines (1837 loc) · 71.1 KB
/
mapmssql2008.c
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
/******************************************************************************
* $Id$
*
* Project: MapServer
* Purpose: MS SQL 2008 (Katmai) Layer Connector
* Author: Richard Hillman - based on PostGIS and SpatialDB connectors
*
******************************************************************************
* Copyright (c) 2007 IS Consulting (www.mapdotnet.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies of this Software or works derived from this Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
******************************************************************************
*
* Revision 1.0 2007/7/1
* Created.
*
*/
#define _CRT_SECURE_NO_WARNINGS 1
/* $Id$ */
#include <assert.h>
#include "mapserver.h"
#include "maptime.h"
#ifdef USE_MSSQL2008
#include <windows.h>
#include <sql.h>
#include <sqlext.h>
#include <sqltypes.h>
#include <string.h>
#include <ctype.h> /* tolower() */
/* Native geometry parser macros */
/* parser error codes */
#define NOERROR 0
#define NOT_ENOUGH_DATA 1
#define CORRUPT_DATA 2
#define UNSUPPORTED_GEOMETRY_TYPE 3
/* geometry format to transfer geometry column */
#define MSSQLGEOMETRY_NATIVE 0
#define MSSQLGEOMETRY_WKB 1
#define MSSQLGEOMETRY_WKT 2
/* geometry column types */
#define MSSQLCOLTYPE_GEOMETRY 0
#define MSSQLCOLTYPE_GEOGRAPHY 1
#define MSSQLCOLTYPE_BINARY 2
#define MSSQLCOLTYPE_TEXT 3
#define SP_NONE 0
#define SP_HASZVALUES 1
#define SP_HASMVALUES 2
#define SP_ISVALID 4
#define SP_ISSINGLEPOINT 8
#define SP_ISSINGLELINESEGMENT 0x10
#define SP_ISWHOLEGLOBE 0x20
#define ST_UNKNOWN 0
#define ST_POINT 1
#define ST_LINESTRING 2
#define ST_POLYGON 3
#define ST_MULTIPOINT 4
#define ST_MULTILINESTRING 5
#define ST_MULTIPOLYGON 6
#define ST_GEOMETRYCOLLECTION 7
#define ReadInt32(nPos) (*((unsigned int*)(gpi->pszData + (nPos))))
#define ReadByte(nPos) (gpi->pszData[nPos])
#define ReadDouble(nPos) (*((double*)(gpi->pszData + (nPos))))
#define ParentOffset(iShape) (ReadInt32(gpi->nShapePos + (iShape) * 9 ))
#define FigureOffset(iShape) (ReadInt32(gpi->nShapePos + (iShape) * 9 + 4))
#define ShapeType(iShape) (ReadByte(gpi->nShapePos + (iShape) * 9 + 8))
#define NextFigureOffset(iShape) (iShape + 1 < gpi->nNumShapes? FigureOffset((iShape) +1) : gpi->nNumFigures)
#define FigureAttribute(iFigure) (ReadByte(gpi->nFigurePos + (iFigure) * 5))
#define PointOffset(iFigure) (ReadInt32(gpi->nFigurePos + (iFigure) * 5 + 1))
#define NextPointOffset(iFigure) (iFigure + 1 < gpi->nNumFigures? PointOffset((iFigure) +1) : gpi->nNumPoints)
#define ReadX(iPoint) (ReadDouble(gpi->nPointPos + 16 * (iPoint)))
#define ReadY(iPoint) (ReadDouble(gpi->nPointPos + 16 * (iPoint) + 8))
#define ReadZ(iPoint) (ReadDouble(gpi->nPointPos + 16 * gpi->nNumPoints + 8 * (iPoint)))
#define ReadM(iPoint) (ReadDouble(gpi->nPointPos + 24 * gpi->nNumPoints + 8 * (iPoint)))
/* Native geometry parser struct */
typedef struct msGeometryParserInfo_t {
unsigned char* pszData;
int nLen;
/* serialization propeties */
char chProps;
/* point array */
int nPointSize;
int nPointPos;
int nNumPoints;
/* figure array */
int nFigurePos;
int nNumFigures;
/* shape array */
int nShapePos;
int nNumShapes;
int nSRSId;
/* geometry or geography */
int nColType;
/* bounds */
double minx;
double miny;
double maxx;
double maxy;
} msGeometryParserInfo;
/* Structure for connection to an ODBC database (Microsoft preferred way to connect to SQL Server 2005 from c/c++) */
typedef struct msODBCconn_t {
SQLHENV henv; /* ODBC HENV */
SQLHDBC hdbc; /* ODBC HDBC */
SQLHSTMT hstmt; /* ODBC HSTMNT */
char errorMessage[1024]; /* Last error message if any */
} msODBCconn;
typedef struct ms_MSSQL2008_layer_info_t {
char *sql; /* sql query to send to DB */
long row_num; /* what row is the NEXT to be read (for random access) */
char *geom_column; /* name of the actual geometry column parsed from the LAYER's DATA field */
char *geom_column_type; /* the type of the geometry column */
char *geom_table; /* the table name or sub-select decalred in the LAYER's DATA field */
char *urid_name; /* name of user-specified unique identifier or OID */
char *user_srid; /* zero length = calculate, non-zero means using this value! */
char *index_name; /* hopefully this isn't necessary - but if the optimizer ain't cuttin' it... */
msODBCconn * conn; /* Connection to db */
msGeometryParserInfo gpi; /* struct for the geometry parser */
int geometry_format; /* Geometry format to be retrieved from the database */
} msMSSQL2008LayerInfo;
#define SQL_COLUMN_NAME_MAX_LENGTH 128
#define SQL_TABLE_NAME_MAX_LENGTH 128
#define DATA_ERROR_MESSAGE \
"%s" \
"Error with MSSQL2008 data variable. You specified '%s'.<br>\n" \
"Standard ways of specifiying are : <br>\n(1) 'geometry_column from geometry_table' <br>\n(2) 'geometry_column from (<sub query>) as foo using unique <column name> using SRID=<srid#>' <br><br>\n\n" \
"Make sure you utilize the 'using unique <column name>' and 'using with <index name>' clauses in.\n\n<br><br>" \
"For more help, please see http://www.mapdotnet.com \n\n<br><br>" \
"mapmssql2008.c - version of 2007/7/1.\n"
/* Native geometry parser code */
void ReadPoint(msGeometryParserInfo* gpi, pointObj* p, int iPoint, int iOrder)
{
if (gpi->nColType == MSSQLCOLTYPE_GEOGRAPHY) {
p->x = ReadY(iPoint);
p->y = ReadX(iPoint);
} else {
p->x = ReadX(iPoint);
p->y = ReadY(iPoint);
}
/* calculate bounds */
if (iOrder == 0) {
gpi->minx = gpi->maxx = p->x;
gpi->miny = gpi->maxy = p->y;
} else {
if (gpi->minx > p->x) gpi->minx = p->x;
else if (gpi->maxx < p->x) gpi->maxx = p->x;
if (gpi->miny > p->y) gpi->miny = p->y;
else if (gpi->maxy < p->y) gpi->maxy = p->y;
}
#ifdef USE_POINT_Z_M
if ( gpi->chProps & SP_HASZVALUES )
p->z = ReadZ(iPoint);
if ( gpi->chProps & SP_HASMVALUES )
p->z = ReadM(iPoint);
#endif
}
int ParseSqlGeometry(msMSSQL2008LayerInfo* layerinfo, shapeObj *shape)
{
msGeometryParserInfo* gpi = &layerinfo->gpi;
if (gpi->nLen < 10) {
msDebug("ParseSqlGeometry NOT_ENOUGH_DATA\n");
return NOT_ENOUGH_DATA;
}
/* store the SRS id for further use */
gpi->nSRSId = ReadInt32(0);
if ( ReadByte(4) != 1 ) {
msDebug("ParseSqlGeometry CORRUPT_DATA\n");
return CORRUPT_DATA;
}
gpi->chProps = ReadByte(5);
if ( gpi->chProps & SP_HASMVALUES )
gpi->nPointSize = 32;
else if ( gpi->chProps & SP_HASZVALUES )
gpi->nPointSize = 24;
else
gpi->nPointSize = 16;
if ( gpi->chProps & SP_ISSINGLEPOINT ) {
// single point geometry
gpi->nNumPoints = 1;
if (gpi->nLen < 6 + gpi->nPointSize) {
msDebug("ParseSqlGeometry NOT_ENOUGH_DATA\n");
return NOT_ENOUGH_DATA;
}
shape->type = MS_SHAPE_POINT;
shape->line = (lineObj *) msSmallMalloc(sizeof(lineObj));
shape->numlines = 1;
shape->line[0].point = (pointObj *) msSmallMalloc(sizeof(pointObj));
shape->line[0].numpoints = 1;
gpi->nPointPos = 6;
ReadPoint(gpi, &shape->line[0].point[0], 0, 0);
} else if ( gpi->chProps & SP_ISSINGLELINESEGMENT ) {
// single line segment with 2 points
gpi->nNumPoints = 2;
if (gpi->nLen < 6 + 2 * gpi->nPointSize) {
msDebug("ParseSqlGeometry NOT_ENOUGH_DATA\n");
return NOT_ENOUGH_DATA;
}
shape->type = MS_SHAPE_LINE;
shape->line = (lineObj *) msSmallMalloc(sizeof(lineObj));
shape->numlines = 1;
shape->line[0].point = (pointObj *) msSmallMalloc(sizeof(pointObj) * 2);
shape->line[0].numpoints = 2;
gpi->nPointPos = 6;
ReadPoint(gpi, &shape->line[0].point[0], 0, 0);
ReadPoint(gpi, &shape->line[0].point[1], 1, 1);
} else {
int iShape, iFigure;
// complex geometries
gpi->nNumPoints = ReadInt32(6);
if ( gpi->nNumPoints <= 0 ) {
return NOERROR;
}
// position of the point array
gpi->nPointPos = 10;
// position of the figures
gpi->nFigurePos = gpi->nPointPos + gpi->nPointSize * gpi->nNumPoints + 4;
if (gpi->nLen < gpi->nFigurePos) {
msDebug("ParseSqlGeometry NOT_ENOUGH_DATA\n");
return NOT_ENOUGH_DATA;
}
gpi->nNumFigures = ReadInt32(gpi->nFigurePos - 4);
if ( gpi->nNumFigures <= 0 ) {
return NOERROR;
}
// position of the shapes
gpi->nShapePos = gpi->nFigurePos + 5 * gpi->nNumFigures + 4;
if (gpi->nLen < gpi->nShapePos) {
msDebug("ParseSqlGeometry NOT_ENOUGH_DATA\n");
return NOT_ENOUGH_DATA;
}
gpi->nNumShapes = ReadInt32(gpi->nShapePos - 4);
if (gpi->nLen < gpi->nShapePos + 9 * gpi->nNumShapes) {
msDebug("ParseSqlGeometry NOT_ENOUGH_DATA\n");
return NOT_ENOUGH_DATA;
}
if ( gpi->nNumShapes <= 0 ) {
return NOERROR;
}
// pick up the root shape
if ( ParentOffset(0) != 0xFFFFFFFF) {
msDebug("ParseSqlGeometry CORRUPT_DATA\n");
return CORRUPT_DATA;
}
// determine the shape type
for (iShape = 0; iShape < gpi->nNumShapes; iShape++) {
unsigned char shapeType = ShapeType(iShape);
if (shapeType == ST_POINT || shapeType == ST_MULTIPOINT) {
shape->type = MS_SHAPE_POINT;
break;
} else if (shapeType == ST_LINESTRING || shapeType == ST_MULTILINESTRING) {
shape->type = MS_SHAPE_LINE;
break;
} else if (shapeType == ST_POLYGON || shapeType == ST_MULTIPOLYGON) {
shape->type = MS_SHAPE_POLYGON;
break;
}
}
shape->line = (lineObj *) msSmallMalloc(sizeof(lineObj) * gpi->nNumFigures);
shape->numlines = gpi->nNumFigures;
// read figures
for (iFigure = 0; iFigure < gpi->nNumFigures; iFigure++) {
int iPoint, iNextPoint, i;
iPoint = PointOffset(iFigure);
iNextPoint = NextPointOffset(iFigure);
shape->line[iFigure].point = (pointObj *) msSmallMalloc(sizeof(pointObj)*(iNextPoint - iPoint));
i = 0;
while (iPoint < iNextPoint) {
ReadPoint(gpi, &shape->line[iFigure].point[i], iPoint, i);
++iPoint;
++i;
}
shape->line[iFigure].numpoints = i;
}
}
/* set bounds */
shape->bounds.minx = gpi->minx;
shape->bounds.miny = gpi->miny;
shape->bounds.maxx = gpi->maxx;
shape->bounds.maxy = gpi->maxy;
return NOERROR;
}
/* MS SQL driver code*/
msMSSQL2008LayerInfo *getMSSQL2008LayerInfo(const layerObj *layer)
{
return layer->layerinfo;
}
void setMSSQL2008LayerInfo(layerObj *layer, msMSSQL2008LayerInfo *MSSQL2008layerinfo)
{
layer->layerinfo = (void*) MSSQL2008layerinfo;
}
void handleSQLError(layerObj *layer)
{
SQLCHAR SqlState[6], Msg[SQL_MAX_MESSAGE_LENGTH];
SQLINTEGER NativeError;
SQLSMALLINT i, MsgLen;
SQLRETURN rc;
msMSSQL2008LayerInfo *layerinfo = getMSSQL2008LayerInfo(layer);
if (layerinfo == NULL)
return;
// Get the status records.
i = 1;
while ((rc = SQLGetDiagRec(SQL_HANDLE_STMT, layerinfo->conn->hstmt, i, SqlState, &NativeError,
Msg, sizeof(Msg), &MsgLen)) != SQL_NO_DATA) {
if(layer->debug) {
msDebug("SQLError: %s\n", Msg);
}
i++;
}
}
/* remove white space */
/* dont send in empty strings or strings with just " " in them! */
static char* removeWhite(char *str)
{
int initial;
char *orig, *loc;
initial = strspn(str, " ");
if(initial) {
memmove(str, str + initial, strlen(str) - initial + 1);
}
/* now final */
if(strlen(str) == 0) {
return str;
}
if(str[strlen(str) - 1] == ' ') {
/* have to remove from end */
orig = str;
loc = &str[strlen(str) - 1];
while((*loc = ' ') && (loc >orig)) {
*loc = 0;
loc--;
}
}
return str;
}
/* TODO Take a look at glibc's strcasestr */
static char *strstrIgnoreCase(const char *haystack, const char *needle)
{
char *hay_lower;
char *needle_lower;
int len_hay,len_need;
int t;
char *loc;
int match = -1;
len_hay = strlen(haystack);
len_need = strlen(needle);
hay_lower = (char*) msSmallMalloc(len_hay + 1);
needle_lower =(char*) msSmallMalloc(len_need + 1);
for(t = 0; t < len_hay; t++) {
hay_lower[t] = (char)tolower(haystack[t]);
}
hay_lower[t] = 0;
for(t = 0; t < len_need; t++) {
needle_lower[t] = (char)tolower(needle[t]);
}
needle_lower[t] = 0;
loc = strstr(hay_lower, needle_lower);
if(loc) {
match = loc - hay_lower;
}
msFree(hay_lower);
msFree(needle_lower);
return (char *) (match < 0 ? NULL : haystack + match);
}
static int msMSSQL2008LayerParseData(layerObj *layer, char **geom_column_name, char **geom_column_type, char **table_name, char **urid_name, char **user_srid, char **index_name, int debug);
/* Close connection and handles */
static void msMSSQL2008CloseConnection(void *conn_handle)
{
msODBCconn * conn = (msODBCconn *) conn_handle;
if (!conn) {
return;
}
if (conn->hstmt) {
SQLFreeHandle(SQL_HANDLE_STMT, conn->hstmt);
}
if (conn->hdbc) {
SQLDisconnect(conn->hdbc);
SQLFreeHandle(SQL_HANDLE_DBC, conn->hdbc);
}
if (conn->henv) {
SQLFreeHandle(SQL_HANDLE_ENV, conn->henv);
}
msFree(conn);
}
/* Set the error string for the connection */
static void setConnError(msODBCconn *conn)
{
SQLSMALLINT len;
SQLGetDiagField(SQL_HANDLE_DBC, conn->hdbc, 1, SQL_DIAG_MESSAGE_TEXT, (SQLPOINTER) conn->errorMessage, sizeof(conn->errorMessage), &len);
conn->errorMessage[len] = 0;
}
/* Connect to db */
static msODBCconn * mssql2008Connect(const char * connString)
{
SQLCHAR fullConnString[1024];
SQLRETURN rc;
msODBCconn * conn = msSmallMalloc(sizeof(msODBCconn));
memset(conn, 0, sizeof(*conn));
SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &conn->henv);
SQLSetEnvAttr(conn->henv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER) SQL_OV_ODBC3, 0);
SQLAllocHandle(SQL_HANDLE_DBC, conn->henv, &conn->hdbc);
snprintf((char*)fullConnString, sizeof(fullConnString), "DRIVER=SQL Server;%s", connString);
{
SQLCHAR outConnString[1024];
SQLSMALLINT outConnStringLen;
rc = SQLDriverConnect(conn->hdbc, NULL, fullConnString, SQL_NTS, outConnString, 1024, &outConnStringLen, SQL_DRIVER_NOPROMPT);
}
if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) {
setConnError(conn);
return conn;
}
SQLAllocHandle(SQL_HANDLE_STMT, conn->hdbc, &conn->hstmt);
return conn;
}
/* Set the error string for the statement execution */
static void setStmntError(msODBCconn *conn)
{
SQLSMALLINT len;
SQLGetDiagField(SQL_HANDLE_STMT, conn->hstmt, 1, SQL_DIAG_MESSAGE_TEXT, (SQLPOINTER) conn->errorMessage, sizeof(conn->errorMessage), &len);
conn->errorMessage[len] = 0;
}
/* Execute SQL against connection. Set error string if failed */
static int executeSQL(msODBCconn *conn, const char * sql)
{
SQLRETURN rc;
SQLCloseCursor(conn->hstmt);
rc = SQLExecDirect(conn->hstmt, (SQLCHAR *) sql, SQL_NTS);
if (rc == SQL_SUCCESS || rc == SQL_SUCCESS_WITH_INFO) {
return 1;
} else {
setStmntError(conn);
return 0;
}
}
/* Get columns name from query results */
static int columnName(msODBCconn *conn, int index, char *buffer, int bufferLength)
{
SQLRETURN rc;
SQLCHAR columnName[SQL_COLUMN_NAME_MAX_LENGTH + 1];
SQLSMALLINT columnNameLen;
SQLSMALLINT dataType;
SQLUINTEGER columnSize;
SQLSMALLINT decimalDigits;
SQLSMALLINT nullable;
rc = SQLDescribeCol(
conn->hstmt,
(SQLUSMALLINT)index,
columnName,
SQL_COLUMN_NAME_MAX_LENGTH,
&columnNameLen,
&dataType,
&columnSize,
&decimalDigits,
&nullable);
if (rc == SQL_SUCCESS || rc == SQL_SUCCESS_WITH_INFO) {
if (bufferLength < SQL_COLUMN_NAME_MAX_LENGTH + 1)
strlcpy(buffer, (const char *)columnName, bufferLength);
else
strlcpy(buffer, (const char *)columnName, SQL_COLUMN_NAME_MAX_LENGTH + 1);
return 1;
} else {
setStmntError(conn);
return 0;
}
}
/* open up a connection to the MS SQL 2008 database using the connection string in layer->connection */
/* ie. "driver=<driver>;server=<server>;database=<database>;integrated security=?;user id=<username>;password=<password>" */
int msMSSQL2008LayerOpen(layerObj *layer)
{
msMSSQL2008LayerInfo *layerinfo;
char *index, *maskeddata;
int i, count;
char *conn_decrypted = NULL;
if(layer->debug) {
msDebug("msMSSQL2008LayerOpen called datastatement: %s\n", layer->data);
}
if(getMSSQL2008LayerInfo(layer)) {
if(layer->debug) {
msDebug("msMSSQL2008LayerOpen :: layer is already open!!\n");
}
return MS_SUCCESS; /* already open */
}
if(!layer->data) {
msSetError(MS_QUERYERR, DATA_ERROR_MESSAGE, "msMSSQL2008LayerOpen()", "", "Error parsing MSSQL2008 data variable: nothing specified in DATA statement.<br><br>\n\nMore Help:<br><br>\n\n");
return MS_FAILURE;
}
if(!layer->connection) {
msSetError( MS_QUERYERR, "MSSQL connection parameter not specified.", "msMSSQL2008LayerOpen()");
return MS_FAILURE;
}
/* have to setup a connection to the database */
layerinfo = (msMSSQL2008LayerInfo*) msSmallMalloc(sizeof(msMSSQL2008LayerInfo));
layerinfo->sql = NULL; /* calc later */
layerinfo->row_num = 0;
layerinfo->geom_column = NULL;
layerinfo->geom_column_type = NULL;
layerinfo->geom_table = NULL;
layerinfo->urid_name = NULL;
layerinfo->user_srid = NULL;
layerinfo->index_name = NULL;
layerinfo->conn = NULL;
layerinfo->conn = (msODBCconn *) msConnPoolRequest(layer);
if(!layerinfo->conn) {
if(layer->debug) {
msDebug("MSMSSQL2008LayerOpen -- shared connection not available.\n");
}
/* Decrypt any encrypted token in connection and attempt to connect */
conn_decrypted = msDecryptStringTokens(layer->map, layer->connection);
if (conn_decrypted == NULL) {
return(MS_FAILURE); /* An error should already have been produced */
}
layerinfo->conn = mssql2008Connect(conn_decrypted);
msFree(conn_decrypted);
conn_decrypted = NULL;
if(!layerinfo->conn || layerinfo->conn->errorMessage[0]) {
char *errMess = "Out of memory";
msDebug("FAILURE!!!");
maskeddata = (char *)msSmallMalloc(strlen(layer->connection) + 1);
strcpy(maskeddata, layer->connection);
index = strstr(maskeddata, "password=");
if(index != NULL) {
index = (char *)(index + 9);
count = (int)(strstr(index, " ") - index);
for(i = 0; i < count; i++) {
strlcpy(index, "*", (int)1);
index++;
}
}
if (layerinfo->conn) {
errMess = layerinfo->conn->errorMessage;
}
msSetError(MS_QUERYERR,
"Couldnt make connection to MS SQL Server 2008 with connect string '%s'.\n<br>\n"
"Error reported was '%s'.\n<br>\n\n"
"This error occured when trying to make a connection to the specified SQL server. \n"
"<br>\nMost commonly this is caused by <br>\n"
"(1) incorrect connection string <br>\n"
"(2) you didnt specify a 'user id=...' in your connection string <br>\n"
"(3) SQL server isnt running <br>\n"
"(4) TCPIP not enabled for SQL Client or server <br>\n\n",
"msMSSQL2008LayerOpen()", maskeddata, errMess);
msFree(maskeddata);
msMSSQL2008CloseConnection(layerinfo->conn);
msFree(layerinfo);
return MS_FAILURE;
}
msConnPoolRegister(layer, layerinfo->conn, msMSSQL2008CloseConnection);
}
setMSSQL2008LayerInfo(layer, layerinfo);
if (msMSSQL2008LayerParseData(layer, &layerinfo->geom_column, &layerinfo->geom_column_type, &layerinfo->geom_table, &layerinfo->urid_name, &layerinfo->user_srid, &layerinfo->index_name, layer->debug) != MS_SUCCESS) {
msSetError( MS_QUERYERR, "Could not parse the layer data", "msMSSQL2008LayerOpen()");
return MS_FAILURE;
}
/* identify the geometry transfer type */
if (msLayerGetProcessingKey( layer, "MSSQL_READ_WKB" ) != NULL)
layerinfo->geometry_format = MSSQLGEOMETRY_WKB;
else {
layerinfo->geometry_format = MSSQLGEOMETRY_NATIVE;
if (strcasecmp(layerinfo->geom_column_type, "geography") == 0)
layerinfo->gpi.nColType = MSSQLCOLTYPE_GEOGRAPHY;
else
layerinfo->gpi.nColType = MSSQLCOLTYPE_GEOMETRY;
}
return MS_SUCCESS;
}
/* Return MS_TRUE if layer is open, MS_FALSE otherwise. */
int msMSSQL2008LayerIsOpen(layerObj *layer)
{
return getMSSQL2008LayerInfo(layer) ? MS_TRUE : MS_FALSE;
}
/* Free the itemindexes array in a layer. */
void msMSSQL2008LayerFreeItemInfo(layerObj *layer)
{
if(layer->debug) {
msDebug("msMSSQL2008LayerFreeItemInfo called\n");
}
if(layer->iteminfo) {
msFree(layer->iteminfo);
}
layer->iteminfo = NULL;
}
/* allocate the iteminfo index array - same order as the item list */
int msMSSQL2008LayerInitItemInfo(layerObj *layer)
{
int i;
int *itemindexes ;
if (layer->debug) {
msDebug("msMSSQL2008LayerInitItemInfo called\n");
}
if(layer->numitems == 0) {
return MS_SUCCESS;
}
msFree(layer->iteminfo);
layer->iteminfo = (int *) msSmallMalloc(sizeof(int) * layer->numitems);
itemindexes = (int*)layer->iteminfo;
for(i = 0; i < layer->numitems; i++) {
itemindexes[i] = i; /* last one is always the geometry one - the rest are non-geom */
}
return MS_SUCCESS;
}
/* Prepare and execute the SQL statement for this layer */
static int prepare_database(layerObj *layer, rectObj rect, char **query_string)
{
msMSSQL2008LayerInfo *layerinfo;
char *columns_wanted = 0;
char *data_source = 0;
char *f_table_name = 0;
char *geom_table = 0;
/*
"Geometry::STGeomFromText('POLYGON(())',)" + terminator = 40 chars
Plus 10 formatted doubles (15 digits of precision, a decimal point, a space/comma delimiter each = 17 chars each)
Plus SRID + comma - if SRID is a long...we'll be safe with 10 chars
*/
char box3d[40 + 10 * 22 + 11];
char query_string_temp[10000]; /* Should be big enough */
int t;
char *pos_from, *pos_ftab, *pos_space, *pos_paren;
rectObj extent;
layerinfo = getMSSQL2008LayerInfo(layer);
/* Extract the proper f_table_name from the geom_table string.
* We are expecting the geom_table to be either a single word
* or a sub-select clause that possibly includes a join --
*
* (select column[,column[,...]] from ftab[ natural join table2]) as foo
*
* We are expecting whitespace or a ')' after the ftab name.
*
*/
geom_table = msStrdup(layerinfo->geom_table);
pos_from = strstrIgnoreCase(geom_table, " from ");
if(!pos_from) {
f_table_name = (char *) msSmallMalloc(strlen(geom_table) + 1);
strcpy(f_table_name, geom_table);
} else { /* geom_table is a sub-select clause */
pos_ftab = pos_from + 6; /* This should be the start of the ftab name */
pos_space = strstr(pos_ftab, " "); /* First space */
/* TODO strrchr is POSIX and C99, rindex is neither */
#if defined(_WIN32) && !defined(__CYGWIN__)
pos_paren = strrchr(pos_ftab, ')');
#else
pos_paren = rindex(pos_ftab, ')');
#endif
if(!pos_space || !pos_paren) {
msSetError(MS_QUERYERR, DATA_ERROR_MESSAGE, "prepare_database()", geom_table, "Error parsing MSSQL2008 data variable: Something is wrong with your subselect statement.<br><br>\n\nMore Help:<br><br>\n\n");
return MS_FAILURE;
}
if (pos_paren < pos_space) { /* closing parenthesis preceeds any space */
f_table_name = (char *) msSmallMalloc(pos_paren - pos_ftab + 1);
strlcpy(f_table_name, pos_ftab, pos_paren - pos_ftab + 1);
} else {
f_table_name = (char *) msSmallMalloc(pos_space - pos_ftab + 1);
strlcpy(f_table_name, pos_ftab, pos_space - pos_ftab + 1);
}
}
if(layer->numitems == 0) {
char buffer[1000];
if (layerinfo->geometry_format == MSSQLGEOMETRY_NATIVE)
snprintf(buffer, sizeof(buffer), "[%s],convert(varchar(36), [%s])", layerinfo->geom_column, layerinfo->urid_name);
else
snprintf(buffer, sizeof(buffer), "[%s].STAsBinary(),convert(varchar(36), [%s])", layerinfo->geom_column, layerinfo->urid_name);
columns_wanted = msStrdup(buffer);
} else {
char buffer[10000] = "";
for(t = 0; t < layer->numitems; t++) {
snprintf(buffer + strlen(buffer), sizeof(buffer) - strlen(buffer), "convert(varchar(max), [%s]),", layer->items[t]);
}
if (layerinfo->geometry_format == MSSQLGEOMETRY_NATIVE)
snprintf(buffer + strlen(buffer), sizeof(buffer) - strlen(buffer), "[%s],convert(varchar(36), [%s])", layerinfo->geom_column, layerinfo->urid_name);
else
snprintf(buffer + strlen(buffer), sizeof(buffer) - strlen(buffer), "[%s].STAsBinary(),convert(varchar(36), [%s])", layerinfo->geom_column, layerinfo->urid_name);
columns_wanted = msStrdup(buffer);
}
if (rect.minx == rect.maxx || rect.miny == rect.maxy) {
/* create point shape for rectangles with zero area */
sprintf(box3d, "%s::STGeomFromText('POINT(%.15g %.15g)',%s)", /* %s.STSrid)", */
layerinfo->geom_column_type, rect.minx, rect.miny, layerinfo->user_srid);
} else {
sprintf(box3d, "%s::STGeomFromText('POLYGON((%.15g %.15g,%.15g %.15g,%.15g %.15g,%.15g %.15g,%.15g %.15g))',%s)", /* %s.STSrid)", */
layerinfo->geom_column_type,
rect.minx, rect.miny,
rect.maxx, rect.miny,
rect.maxx, rect.maxy,
rect.minx, rect.maxy,
rect.minx, rect.miny,
layerinfo->user_srid
);
}
/* substitute token '!BOX!' in geom_table with the box3d - do an unlimited # of subs */
/* to not undo the work here, we need to make sure that data_source is malloc'd here */
if(!strstr(geom_table, "!BOX!")) {
data_source = (char *) msSmallMalloc(strlen(geom_table) + 1);
strcpy(data_source, geom_table);
} else {
char* result = NULL;
while (strstr(geom_table,"!BOX!")) {
/* need to do a substition */
char *start, *end;
char *oldresult = result;
start = strstr(geom_table,"!BOX!");
end = start+5;
result = (char *)msSmallMalloc((start - geom_table) + strlen(box3d) + strlen(end) +1);
strlcpy(result, geom_table, start - geom_table + 1);
strcpy(result + (start - geom_table), box3d);
strcat(result, end);
geom_table= result;
msFree(oldresult);
}
/* if we're here, this will be a malloc'd string, so no need to copy it */
data_source = (char *)geom_table;
}
/* use the index hint if provided */
if ( layerinfo->index_name ) {
/* given the template - figure out how much to malloc and malloc it */
char *with_template = "%s WITH (INDEX(%s))";
int need_len = strlen(data_source) + strlen(with_template) + strlen(layerinfo->index_name);
char *tmp = (char*) msSmallMalloc( need_len + 1 );
sprintf( tmp, with_template, data_source, layerinfo->index_name );
msFree(data_source);
data_source = tmp;
}
/* test whether we should omit spatial filtering */
msMSSQL2008LayerGetExtent(layer, &extent);
if (rect.minx <= extent.minx && rect.miny <= extent.miny &&
rect.maxx >= extent.maxx && rect.maxy >= extent.maxy) {
/* no spatial filter used */
if(!layer->filter.string) {
snprintf(query_string_temp, sizeof(query_string_temp), "SELECT %s from %s", columns_wanted, data_source );
} else {
snprintf(query_string_temp, sizeof(query_string_temp), "SELECT %s from %s WHERE (%s)", columns_wanted, data_source, layer->filter.string );
}
}
else {
if(!layer->filter.string) {
snprintf(query_string_temp, sizeof(query_string_temp), "SELECT %s from %s WHERE %s.STIntersects(%s) = 1 ", columns_wanted, data_source, layerinfo->geom_column, box3d );
} else {
snprintf(query_string_temp, sizeof(query_string_temp), "SELECT %s from %s WHERE (%s) and %s.STIntersects(%s) = 1 ", columns_wanted, data_source, layer->filter.string, layerinfo->geom_column, box3d );
}
}
msFree(data_source);
msFree(f_table_name);
msFree(columns_wanted);
if(layer->debug) {
msDebug("query_string_temp:%s\n", query_string_temp);
}
if (executeSQL(layerinfo->conn, query_string_temp)) {
*query_string = msStrdup(query_string_temp);
return MS_SUCCESS;
} else {
msSetError(MS_QUERYERR, "Error executing MSSQL2008 SQL statement: %s\n-%s\n", "msMSSQL2008LayerGetShape()", query_string_temp, layerinfo->conn->errorMessage);
return MS_FAILURE;
}
}
/* Execute SQL query for this layer */
int msMSSQL2008LayerWhichShapes(layerObj *layer, rectObj rect, int isQuery)
{
msMSSQL2008LayerInfo *layerinfo = 0;
char *query_str = 0;
int set_up_result;
if(layer->debug) {
msDebug("msMSSQL2008LayerWhichShapes called\n");
}
layerinfo = getMSSQL2008LayerInfo(layer);
if(!layerinfo) {
/* layer not opened yet */
msSetError(MS_QUERYERR, "msMSSQL2008LayerWhichShapes called on unopened layer (layerinfo = NULL)", "msMSSQL2008LayerWhichShapes()");
return MS_FAILURE;
}
if(!layer->data) {
msSetError(MS_QUERYERR, "Missing DATA clause in MSSQL2008 Layer definition. DATA statement must contain 'geometry_column from table_name' or 'geometry_column from (sub-query) as foo'.", "msMSSQL2008LayerWhichShapes()");
return MS_FAILURE;
}
set_up_result = prepare_database(layer, rect, &query_str);
if(set_up_result != MS_SUCCESS) {
msFree(query_str);
return set_up_result; /* relay error */
}
msFree(layerinfo->sql);
layerinfo->sql = query_str;
layerinfo->row_num = 0;
return MS_SUCCESS;
}
/* Close the MSSQL2008 record set and connection */
int msMSSQL2008LayerClose(layerObj *layer)
{
msMSSQL2008LayerInfo *layerinfo;
layerinfo = getMSSQL2008LayerInfo(layer);
if(layer->debug) {
char *data = "";
if (layer->data) {
data = layer->data;
}
msDebug("msMSSQL2008LayerClose datastatement: %s\n", data);
}
if(layer->debug && !layerinfo) {