forked from dmorissette/mapserver
-
Notifications
You must be signed in to change notification settings - Fork 1
/
mapmssql2008.c
3773 lines (3142 loc) · 124 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 Server Layer Connector
* Author: Richard Hillman - based on PostGIS and SpatialDB connectors
* Tamas Szekeres - maintenance
*
******************************************************************************
* 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.
*
*/
#ifndef _WIN32
#define _GNU_SOURCE
#endif
#define _CRT_SECURE_NO_WARNINGS 1
/* $Id$ */
#include <assert.h>
#include "mapserver.h"
#include "maptime.h"
#include "mapows.h"
#ifdef USE_MSSQL2008
#ifdef _WIN32
#include <windows.h>
#endif
#include <sql.h>
#include <sqlext.h>
#include <sqltypes.h>
#include <string.h>
#include <ctype.h> /* tolower() */
/* SqlGeometry/SqlGeography serialization format
Simple Point (SerializationProps & IsSinglePoint)
[SRID][0x01][SerializationProps][Point][z][m]
Simple Line Segment (SerializationProps & IsSingleLineSegment)
[SRID][0x01][SerializationProps][Point1][Point2][z1][z2][m1][m2]
Complex Geometries
[SRID][VersionAttribute][SerializationProps][NumPoints][Point1]..[PointN][z1]..[zN][m1]..[mN]
[NumFigures][Figure]..[Figure][NumShapes][Shape]..[Shape]
Complex Geometries (FigureAttribute == Curve)
[SRID][VersionAttribute][SerializationProps][NumPoints][Point1]..[PointN][z1]..[zN][m1]..[mN]
[NumFigures][Figure]..[Figure][NumShapes][Shape]..[Shape][NumSegments][SegmentType]..[SegmentType]
VersionAttribute (1 byte)
0x01 = Katmai (MSSQL2008+)
0x02 = Denali (MSSQL2012+)
SRID
Spatial Reference Id (4 bytes)
SerializationProps (bitmask) 1 byte
0x01 = HasZValues
0x02 = HasMValues
0x04 = IsValid
0x08 = IsSinglePoint
0x10 = IsSingleLineSegment
0x20 = IsLargerThanAHemisphere
Point (2-4)x8 bytes, size depends on SerializationProps & HasZValues & HasMValues
[x][y] - SqlGeometry
[latitude][longitude] - SqlGeography
Figure
[FigureAttribute][PointOffset]
FigureAttribute - Katmai (1 byte)
0x00 = Interior Ring
0x01 = Stroke
0x02 = Exterior Ring
FigureAttribute - Denali (1 byte)
0x00 = None
0x01 = Line
0x02 = Arc
0x03 = Curve
Shape
[ParentFigureOffset][FigureOffset][ShapeType]
ShapeType (1 byte)
0x00 = Unknown
0x01 = Point
0x02 = LineString
0x03 = Polygon
0x04 = MultiPoint
0x05 = MultiLineString
0x06 = MultiPolygon
0x07 = GeometryCollection
-- Denali
0x08 = CircularString
0x09 = CompoundCurve
0x0A = CurvePolygon
0x0B = FullGlobe
SegmentType (1 byte)
0x00 = Line
0x01 = Arc
0x02 = FirstLine
0x03 = FirstArc
*/
/* 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_ISLARGERTHANAHEMISPHERE 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 ST_CIRCULARSTRING 8
#define ST_COMPOUNDCURVE 9
#define ST_CURVEPOLYGON 10
#define ST_FULLGLOBE 11
#define SMT_LINE 0
#define SMT_ARC 1
#define SMT_FIRSTLINE 2
#define SMT_FIRSTARC 3
#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 SegmentType(iSegment) (ReadByte(gpi->nSegmentPos + (iSegment)))
#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)))
#define FP_EPSILON 1e-12
#define SEGMENT_ANGLE 5.0
#define SEGMENT_MINPOINTS 10
/* Native geometry parser struct */
typedef struct msGeometryParserInfo_t {
unsigned char* pszData;
int nLen;
/* version */
char chVersion;
/* serialization properties */
char chProps;
/* point array */
int nPointSize;
int nPointPos;
int nNumPoints;
int nNumPointsRead;
/* figure array */
int nFigurePos;
int nNumFigures;
/* shape array */
int nShapePos;
int nNumShapes;
int nSRSId;
/* segment array */
int nSegmentPos;
int nNumSegments;
/* 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... */
char *sort_spec; /* the sort by specification which should be applied to the generated select statement */
int mssqlversion_major; /* the sql server major version number */
int paging; /* Driver handling of pagination, enabled by default */
SQLSMALLINT *itemtypes; /* storing the sql field types for further reference */
msODBCconn * conn; /* Connection to db */
msGeometryParserInfo gpi; /* struct for the geometry parser */
int geometry_format; /* Geometry format to be retrieved from the database */
tokenListNodeObjPtr current_node; /* filter expression translation */
} 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)
{
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 (gpi->nNumPointsRead++ == 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) && (gpi->chProps & SP_HASMVALUES))
{
p->z = ReadZ(iPoint);
p->m = ReadM(iPoint);
}
else if (gpi->chProps & SP_HASZVALUES)
{
p->z = ReadZ(iPoint);
p->m = 0.0;
}
else if (gpi->chProps & SP_HASMVALUES)
{
p->z = 0.0;
p->m = ReadZ(iPoint);
}
else
{
p->z = 0.0;
p->m = 0.0;
}
#endif
}
int StrokeArcToLine(msGeometryParserInfo* gpi, lineObj* line, int index)
{
if (index > 1) {
double x, y, x1, y1, x2, y2, x3, y3, dxa, dya, sxa, sya, dxb, dyb;
double d, sxb, syb, ox, oy, a1, a3, sa, da, a, radius;
int numpoints;
#ifdef USE_POINT_Z_M
double z;
z = line->point[index].z; /* must be equal for arc segments */
#endif
/* first point */
x1 = line->point[index - 2].x;
y1 = line->point[index - 2].y;
/* second point */
x2 = line->point[index - 1].x;
y2 = line->point[index - 1].y;
/* third point */
x3 = line->point[index].x;
y3 = line->point[index].y;
sxa = (x1 + x2);
sya = (y1 + y2);
dxa = x2 - x1;
dya = y2 - y1;
sxb = (x2 + x3);
syb = (y2 + y3);
dxb = x3 - x2;
dyb = y3 - y2;
d = (dxa * dyb - dya * dxb) * 2;
if (fabs(d) < FP_EPSILON) {
/* points are colinear, nothing to do here */
return index;
}
/* calculating the center of circle */
ox = ((sya - syb) * dya * dyb + sxa * dyb * dxa - sxb * dya * dxb) / d;
oy = ((sxb - sxa) * dxa * dxb + syb * dyb * dxa - sya * dya * dxb) / d;
radius = sqrt((x1 - ox) * (x1 - ox) + (y1 - oy) * (y1 - oy));
/* calculating the angle to be used */
a1 = atan2(y1 - oy, x1 - ox);
a3 = atan2(y3 - oy, x3 - ox);
if (d > 0) {
/* draw counterclockwise */
if (a3 > a1) /* Wrapping past 180? */
sa = a3 - a1;
else
sa = a3 - a1 + 2.0 * M_PI ;
}
else {
if (a3 > a1) /* Wrapping past 180? */
sa = a3 - a1 + 2.0 * M_PI;
else
sa = a3 - a1;
}
numpoints = (int)floor(fabs(sa) * 180 / SEGMENT_ANGLE / M_PI);
if (numpoints < SEGMENT_MINPOINTS)
numpoints = SEGMENT_MINPOINTS;
da = sa / numpoints;
/* extend the point array */
line->numpoints += numpoints - 2;
line->point = msSmallRealloc(line->point, sizeof(pointObj) * line->numpoints);
--index;
a = a1 + da;
while (numpoints > 1) {
line->point[index].x = x = ox + radius * cos(a);
line->point[index].y = y = oy + radius * sin(a);
#ifdef USE_POINT_Z_M
line->point[index].z = z;
#endif
/* calculate bounds */
if (gpi->minx > x) gpi->minx = x;
else if (gpi->maxx < x) gpi->maxx = x;
if (gpi->miny > y) gpi->miny = y;
else if (gpi->maxy < y) gpi->maxy = y;
a += da;
++index;
--numpoints;
}
/* set last point */
line->point[index].x = x3;
line->point[index].y = y3;
#ifdef USE_POINT_Z_M
line->point[index].z = z;
#endif
}
return index;
}
int ParseSqlGeometry(msMSSQL2008LayerInfo* layerinfo, shapeObj *shape)
{
msGeometryParserInfo* gpi = &layerinfo->gpi;
gpi->nNumPointsRead = 0;
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);
gpi->chVersion = ReadByte(4);
if (gpi->chVersion > 2) {
msDebug("ParseSqlGeometry CORRUPT_DATA\n");
return CORRUPT_DATA;
}
gpi->chProps = ReadByte(5);
gpi->nPointSize = 16;
if ( gpi->chProps & SP_HASMVALUES )
gpi->nPointSize += 8;
if ( gpi->chProps & SP_HASZVALUES )
gpi->nPointSize += 8;
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);
} 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);
ReadPoint(gpi, &shape->line[0].point[1], 1);
} else {
int iShape, iFigure, iSegment = 0;
// 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 ||
shapeType == ST_CIRCULARSTRING || shapeType == ST_COMPOUNDCURVE) {
shape->type = MS_SHAPE_LINE;
break;
} else if (shapeType == ST_POLYGON || shapeType == ST_MULTIPOLYGON ||
shapeType == ST_CURVEPOLYGON)
{
shape->type = MS_SHAPE_POLYGON;
break;
}
}
shape->line = (lineObj *) msSmallMalloc(sizeof(lineObj) * gpi->nNumFigures);
shape->numlines = gpi->nNumFigures;
gpi->nNumSegments = 0;
// 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));
shape->line[iFigure].numpoints = iNextPoint - iPoint;
i = 0;
if (gpi->chVersion == 0x02 && FigureAttribute(iFigure) >= 0x02) {
int nPointPrepared = 0;
lineObj* line = &shape->line[iFigure];
if (FigureAttribute(iFigure) == 0x03) {
if (gpi->nNumSegments == 0) {
/* position of the segment types */
gpi->nSegmentPos = gpi->nShapePos + 9 * gpi->nNumShapes + 4;
gpi->nNumSegments = ReadInt32(gpi->nSegmentPos - 4);
if (gpi->nLen < gpi->nSegmentPos + gpi->nNumSegments) {
msDebug("ParseSqlGeometry NOT_ENOUGH_DATA\n");
return NOT_ENOUGH_DATA;
}
iSegment = 0;
}
while (iPoint < iNextPoint && iSegment < gpi->nNumSegments) {
ReadPoint(gpi, &line->point[i], iPoint);
++iPoint;
++nPointPrepared;
if (nPointPrepared == 2 && (SegmentType(iSegment) == SMT_FIRSTLINE || SegmentType(iSegment) == SMT_LINE)) {
++iSegment;
nPointPrepared = 1;
}
else if (nPointPrepared == 3 && (SegmentType(iSegment) == SMT_FIRSTARC || SegmentType(iSegment) == SMT_ARC)) {
i = StrokeArcToLine(gpi, line, i);
++iSegment;
nPointPrepared = 1;
}
++i;
}
}
else {
while (iPoint < iNextPoint) {
ReadPoint(gpi, &line->point[i], iPoint);
++iPoint;
++nPointPrepared;
if (nPointPrepared == 3) {
i = StrokeArcToLine(gpi, line, i);
nPointPrepared = 1;
}
++i;
}
}
}
else {
while (iPoint < iNextPoint) {
ReadPoint(gpi, &shape->line[iFigure].point[i], iPoint);
++iPoint;
++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++;
}
}
/* TODO Take a look at glibc's strcasestr */
static char *strstrIgnoreCase(const char *haystack, const char *needle)
{
char *hay_lower;
char *needle_lower;
size_t len_hay,len_need, match;
int found = MS_FALSE;
int t;
char *loc;
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;
found = MS_TRUE;
}
msFree(hay_lower);
msFree(needle_lower);
return (char *) (found == MS_FALSE ? 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, char **sort_spec, 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(char * connString)
{
SQLCHAR outConnString[1024];
SQLSMALLINT outConnStringLen;
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);
if (strcasestr(connString, "DRIVER=") == 0)
{
SQLCHAR fullConnString[1024];
snprintf((char*)fullConnString, sizeof(fullConnString), "DRIVER={SQL Server};%s", connString);
rc = SQLDriverConnect(conn->hdbc, NULL, fullConnString, SQL_NTS, outConnString, 1024, &outConnStringLen, SQL_DRIVER_NOPROMPT);
}
else
{
rc = SQLDriverConnect(conn->hdbc, NULL, (SQLCHAR*)connString, 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, layerObj *layer, char pass_field_def, SQLSMALLINT *itemType)
{
SQLRETURN rc;
SQLCHAR columnName[SQL_COLUMN_NAME_MAX_LENGTH + 1];
SQLSMALLINT columnNameLen;
SQLSMALLINT dataType;
SQLULEN 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);
*itemType = dataType;
if (pass_field_def) {
char md_item_name[256];
char gml_width[32], gml_precision[32];
const char *gml_type = NULL;
gml_width[0] = '\0';
gml_precision[0] = '\0';
switch( dataType ) {
case SQL_INTEGER:
case SQL_SMALLINT:
case SQL_TINYINT:
gml_type = "Integer";
break;
case SQL_BIGINT:
gml_type = "Long";
break;
case SQL_REAL:
case SQL_FLOAT:
case SQL_DOUBLE:
case SQL_DECIMAL:
case SQL_NUMERIC:
gml_type = "Real";
if( decimalDigits > 0 )
sprintf( gml_precision, "%d", decimalDigits );
break;
case SQL_TYPE_DATE:
gml_type = "Date";
break;
case SQL_TYPE_TIME:
gml_type = "Time";
break;
case SQL_TYPE_TIMESTAMP:
gml_type = "DateTime";
break;
case SQL_BIT:
gml_type = "Boolean";
break;
default:
gml_type = "Character";
break;
}
if( columnSize > 0 )
sprintf( gml_width, "%u", (unsigned int)columnSize );
snprintf( md_item_name, sizeof(md_item_name), "gml_%s_type", buffer );
if( msOWSLookupMetadata(&(layer->metadata), "G", "type") == NULL )
msInsertHashTable(&(layer->metadata), md_item_name, gml_type );
snprintf( md_item_name, sizeof(md_item_name), "gml_%s_width", buffer );
if( strlen(gml_width) > 0
&& msOWSLookupMetadata(&(layer->metadata), "G", "width") == NULL )
msInsertHashTable(&(layer->metadata), md_item_name, gml_width );
snprintf( md_item_name, sizeof(md_item_name), "gml_%s_precision",buffer );
if( strlen(gml_precision) > 0
&& msOWSLookupMetadata(&(layer->metadata), "G", "precision")==NULL )
msInsertHashTable(&(layer->metadata), md_item_name, gml_precision );
snprintf( md_item_name, sizeof(md_item_name), "gml_%s_nillable",buffer );
if( nullable > 0 )
msInsertHashTable(&(layer->metadata), md_item_name, "true" );
}
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->sort_spec = NULL;
layerinfo->conn = NULL;
layerinfo->itemtypes = NULL;
layerinfo->mssqlversion_major = 0;
layerinfo->paging = MS_TRUE;
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;
}