mapjoin.c 24.1 KB
Newer Older
1
/******************************************************************************
2
 * $Id$
3 4
 *
 * Project:  MapServer
5
 * Purpose:  Implements MapServer joins.
6 7 8 9 10 11 12 13 14 15 16 17
 * Author:   Steve Lime and the MapServer team.
 *
 ******************************************************************************
 * Copyright (c) 1996-2005 Regents of the University of Minnesota.
 *
 * 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:
 *
18
 * The above copyright notice and this permission notice shall be included in
19 20 21 22 23 24 25 26 27 28 29 30 31
 * 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.
 ****************************************************************************/

#include "mapserver.h"

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

#define ROW_ALLOCATION_SIZE 10


/* DBF/XBase function prototypes */
int msDBFJoinConnect(layerObj *layer, joinObj *join);
int msDBFJoinPrepare(joinObj *join, shapeObj *shape);
int msDBFJoinNext(joinObj *join);
int msDBFJoinClose(joinObj *join);
int msDBFJoinTable(layerObj *layer, joinObj *join, shapeObj *shape);

/* CSV (comma delimited text file) function prototypes */
int msCSVJoinConnect(layerObj *layer, joinObj *join);
int msCSVJoinPrepare(joinObj *join, shapeObj *shape);
int msCSVJoinNext(joinObj *join);
int msCSVJoinClose(joinObj *join);
int msCSVJoinTable(layerObj *layer, joinObj *join, shapeObj *shape);

/* MySQL function prototypes */
int msMySQLJoinConnect(layerObj *layer, joinObj *join);
int msMySQLJoinPrepare(joinObj *join, shapeObj *shape);
int msMySQLJoinNext(joinObj *join);
int msMySQLJoinClose(joinObj *join);
int msMySQLJoinTable(layerObj *layer, joinObj *join, shapeObj *shape);

/* PostgreSQL function prototypes */
int msPOSTGRESQLJoinConnect(layerObj *layer, joinObj *join);
int msPOSTGRESQLJoinPrepare(joinObj *join, shapeObj *shape);
int msPOSTGRESQLJoinNext(joinObj *join);
int msPOSTGRESQLJoinClose(joinObj *join);

/* wrapper function for DB specific join functions */
65
int msJoinConnect(layerObj *layer, joinObj *join)
66 67
{
  switch(join->connectiontype) {
68 69 70 71 72 73 74 75 76 77 78 79 80 81
    case(MS_DB_XBASE):
      return msDBFJoinConnect(layer, join);
      break;
    case(MS_DB_CSV):
      return msCSVJoinConnect(layer, join);
      break;
    case(MS_DB_MYSQL):
      return msMySQLJoinConnect(layer, join);
      break;
    case(MS_DB_POSTGRES):
      return msPOSTGRESQLJoinConnect(layer, join);
      break;
    default:
      break;
82 83 84 85 86 87
  }

  msSetError(MS_JOINERR, "Unsupported join connection type.", "msJoinConnect()");
  return MS_FAILURE;
}

88
int msJoinPrepare(joinObj *join, shapeObj *shape)
89 90
{
  switch(join->connectiontype) {
91 92 93 94 95 96 97 98 99 100 101 102 103 104
    case(MS_DB_XBASE):
      return msDBFJoinPrepare(join, shape);
      break;
    case(MS_DB_CSV):
      return msCSVJoinPrepare(join, shape);
      break;
    case(MS_DB_MYSQL):
      return msMySQLJoinPrepare(join, shape);
      break;
    case(MS_DB_POSTGRES):
      return msPOSTGRESQLJoinPrepare(join, shape);
      break;
    default:
      break;
105 106 107 108 109 110
  }

  msSetError(MS_JOINERR, "Unsupported join connection type.", "msJoinPrepare()");
  return MS_FAILURE;
}

111
int msJoinNext(joinObj *join)
112 113
{
  switch(join->connectiontype) {
114 115 116 117 118 119 120 121 122 123 124 125 126 127
    case(MS_DB_XBASE):
      return msDBFJoinNext(join);
      break;
    case(MS_DB_CSV):
      return msCSVJoinNext(join);
      break;
    case(MS_DB_MYSQL):
      return msMySQLJoinNext(join);
      break;
    case(MS_DB_POSTGRES):
      return msPOSTGRESQLJoinNext(join);
      break;
    default:
      break;
128 129 130 131 132 133
  }

  msSetError(MS_JOINERR, "Unsupported join connection type.", "msJoinNext()");
  return MS_FAILURE;
}

134
int msJoinClose(joinObj *join)
135 136
{
  switch(join->connectiontype) {
137 138 139 140 141 142 143 144 145 146 147 148 149 150
    case(MS_DB_XBASE):
      return msDBFJoinClose(join);
      break;
    case(MS_DB_CSV):
      return msCSVJoinClose(join);
      break;
    case(MS_DB_MYSQL):
      return msMySQLJoinClose(join);
      break;
    case(MS_DB_POSTGRES):
      return msPOSTGRESQLJoinClose(join);
      break;
    default:
      break;
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
  }

  msSetError(MS_JOINERR, "Unsupported join connection type.", "msJoinClose()");
  return MS_FAILURE;
}

/*  */
/* XBASE join functions */
/*  */
typedef struct {
  DBFHandle hDBF;
  int fromindex, toindex;
  char *target;
  int nextrecord;
} msDBFJoinInfo;

167
int msDBFJoinConnect(layerObj *layer, joinObj *join)
168 169 170 171 172 173
{
  int i;
  char szPath[MS_MAXPATHLEN];
  msDBFJoinInfo *joininfo;

  if(join->joininfo) return(MS_SUCCESS); /* already open */
174

175
  if ( msCheckParentPointer(layer->map,"map")==MS_FAILURE )
176 177 178
    return MS_FAILURE;


179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
  /* allocate a msDBFJoinInfo struct */
  joininfo = (msDBFJoinInfo *) malloc(sizeof(msDBFJoinInfo));
  if(!joininfo) {
    msSetError(MS_MEMERR, "Error allocating XBase table info structure.", "msDBFJoinConnect()");
    return(MS_FAILURE);
  }

  /* initialize any members that won't get set later on in this function */
  joininfo->target = NULL;
  joininfo->nextrecord = 0;

  join->joininfo = joininfo;

  /* open the XBase file */
  if((joininfo->hDBF = msDBFOpen( msBuildPath3(szPath, layer->map->mappath, layer->map->shapepath, join->table), "rb" )) == NULL) {
194 195
    if((joininfo->hDBF = msDBFOpen( msBuildPath(szPath, layer->map->mappath, join->table), "rb" )) == NULL) {
      msSetError(MS_IOERR, "(%s)", "msDBFJoinConnect()", join->table);
196 197 198 199 200
      return(MS_FAILURE);
    }
  }

  /* get "to" item index */
201 202
  if((joininfo->toindex = msDBFGetItemIndex(joininfo->hDBF, join->to)) == -1) {
    msSetError(MS_DBFERR, "Item %s not found in table %s.", "msDBFJoinConnect()", join->to, join->table);
203 204 205 206 207 208 209 210 211 212 213 214
    return(MS_FAILURE);
  }

  /* get "from" item index   */
  for(i=0; i<layer->numitems; i++) {
    if(strcasecmp(layer->items[i],join->from) == 0) { /* found it */
      joininfo->fromindex = i;
      break;
    }
  }

  if(i == layer->numitems) {
215
    msSetError(MS_JOINERR, "Item %s not found in layer %s.", "msDBFJoinConnect()", join->from, layer->name);
216 217 218 219 220 221
    return(MS_FAILURE);
  }

  /* finally store away the item names in the XBase table */
  join->numitems =  msDBFGetFieldCount(joininfo->hDBF);
  join->items = msDBFGetItems(joininfo->hDBF);
222
  if(!join->items) return(MS_FAILURE);
223 224 225 226

  return(MS_SUCCESS);
}

227
int msDBFJoinPrepare(joinObj *join, shapeObj *shape)
228
{
229
  msDBFJoinInfo *joininfo = join->joininfo;
230 231

  if(!joininfo) {
232
    msSetError(MS_JOINERR, "Join connection has not be created.", "msDBFJoinPrepare()");
233 234 235 236
    return(MS_FAILURE);
  }

  if(!shape) {
237
    msSetError(MS_JOINERR, "Shape to be joined is empty.", "msDBFJoinPrepare()");
238 239 240 241
    return(MS_FAILURE);
  }

  if(!shape->values) {
242
    msSetError(MS_JOINERR, "Shape to be joined has no attributes.", "msDBFJoinPrepare()");
243 244 245 246 247 248
    return(MS_FAILURE);
  }

  joininfo->nextrecord = 0; /* starting with the first record */

  if(joininfo->target) free(joininfo->target); /* clear last target */
249
  joininfo->target = msStrdup(shape->values[joininfo->fromindex]);
250 251 252 253

  return(MS_SUCCESS);
}

254
int msDBFJoinNext(joinObj *join)
255 256 257 258 259
{
  int i, n;
  msDBFJoinInfo *joininfo = join->joininfo;

  if(!joininfo) {
260
    msSetError(MS_JOINERR, "Join connection has not be created.", "msDBFJoinNext()");
261 262 263 264 265 266 267 268 269
    return(MS_FAILURE);
  }

  if(!joininfo->target) {
    msSetError(MS_JOINERR, "No target specified, run msDBFJoinPrepare() first.", "msDBFJoinNext()");
    return(MS_FAILURE);
  }

  /* clear any old data */
270
  if(join->values) {
271 272 273 274 275
    msFreeCharArray(join->values, join->numitems);
    join->values = NULL;
  }

  n = msDBFGetRecordCount(joininfo->hDBF);
276

277 278
  for(i=joininfo->nextrecord; i<n; i++) { /* find a match */
    if(strcmp(joininfo->target, msDBFReadStringAttribute(joininfo->hDBF, i, joininfo->toindex)) == 0) break;
279 280
  }

281 282 283 284 285 286
  if(i == n) { /* unable to do the join */
    if((join->values = (char **)malloc(sizeof(char *)*join->numitems)) == NULL) {
      msSetError(MS_MEMERR, NULL, "msDBFJoinNext()");
      return(MS_FAILURE);
    }
    for(i=0; i<join->numitems; i++)
287
      join->values[i] = msStrdup("\0"); /* intialize to zero length strings */
288 289 290 291

    joininfo->nextrecord = n;
    return(MS_DONE);
  }
292 293

  if((join->values = msDBFGetValues(joininfo->hDBF,i)) == NULL)
294 295 296 297 298 299 300
    return(MS_FAILURE);

  joininfo->nextrecord = i+1; /* so we know where to start looking next time through */

  return(MS_SUCCESS);
}

301
int msDBFJoinClose(joinObj *join)
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
{
  msDBFJoinInfo *joininfo = join->joininfo;

  if(!joininfo) return(MS_SUCCESS); /* already closed */

  if(joininfo->hDBF) msDBFClose(joininfo->hDBF);
  if(joininfo->target) free(joininfo->target);
  free(joininfo);
  joininfo = NULL;

  return(MS_SUCCESS);
}

/*  */
/* CSV (comma separated value) join functions */
/*  */
typedef struct {
  int fromindex, toindex;
  char *target;
  char ***rows;
  int numrows;
  int nextrow;
} msCSVJoinInfo;

326
int msCSVJoinConnect(layerObj *layer, joinObj *join)
327 328 329 330 331 332 333 334 335
{
  int i;
  FILE *stream;
  char szPath[MS_MAXPATHLEN];
  msCSVJoinInfo *joininfo;
  char buffer[MS_BUFFER_LENGTH];

  if(join->joininfo) return(MS_SUCCESS); /* already open */
  if ( msCheckParentPointer(layer->map,"map")==MS_FAILURE )
336 337 338
    return MS_FAILURE;


339 340 341 342 343 344 345 346 347 348 349 350 351 352
  /* allocate a msCSVJoinInfo struct */
  if((joininfo = (msCSVJoinInfo *) malloc(sizeof(msCSVJoinInfo))) == NULL) {
    msSetError(MS_MEMERR, "Error allocating CSV table info structure.", "msCSVJoinConnect()");
    return(MS_FAILURE);
  }

  /* initialize any members that won't get set later on in this function */
  joininfo->target = NULL;
  joininfo->nextrow = 0;

  join->joininfo = joininfo;

  /* open the CSV file */
  if((stream = fopen( msBuildPath3(szPath, layer->map->mappath, layer->map->shapepath, join->table), "r" )) == NULL) {
353 354
    if((stream = fopen( msBuildPath(szPath, layer->map->mappath, join->table), "r" )) == NULL) {
      msSetError(MS_IOERR, "(%s)", "msCSVJoinConnect()", join->table);
355 356 357
      return(MS_FAILURE);
    }
  }
358

359 360 361 362 363 364 365 366 367 368 369 370
  /* once through to get the number of rows */
  joininfo->numrows = 0;
  while(fgets(buffer, MS_BUFFER_LENGTH, stream) != NULL) joininfo->numrows++;
  rewind(stream);

  if((joininfo->rows = (char ***) malloc(joininfo->numrows*sizeof(char **))) == NULL) {
    msSetError(MS_MEMERR, "Error allocating rows.", "msCSVJoinConnect()");
    return(MS_FAILURE);
  }

  /* load the rows */
  i = 0;
371 372
  while(fgets(buffer, MS_BUFFER_LENGTH, stream) != NULL) {
    msStringTrimEOL(buffer);
373
    joininfo->rows[i] = msStringSplitComplex(buffer, ",", &(join->numitems), MS_ALLOWEMPTYTOKENS);
374 375 376 377 378 379 380 381 382 383 384 385 386
    i++;
  }
  fclose(stream);

  /* get "from" item index   */
  for(i=0; i<layer->numitems; i++) {
    if(strcasecmp(layer->items[i],join->from) == 0) { /* found it */
      joininfo->fromindex = i;
      break;
    }
  }

  if(i == layer->numitems) {
387
    msSetError(MS_JOINERR, "Item %s not found in layer %s.", "msCSVJoinConnect()", join->from, layer->name);
388 389 390 391 392 393
    return(MS_FAILURE);
  }

  /* get "to" index (for now the user tells us which column, 1..n) */
  joininfo->toindex = atoi(join->to) - 1;
  if(joininfo->toindex < 0 || joininfo->toindex > join->numitems) {
394
    msSetError(MS_JOINERR, "Invalid column index %s.", "msCSVJoinConnect()", join->to);
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
    return(MS_FAILURE);
  }

  /* store away the column names (1..n) */
  if((join->items = (char **) malloc(sizeof(char *)*join->numitems)) == NULL) {
    msSetError(MS_MEMERR, "Error allocating space for join item names.", "msCSVJoinConnect()");
    return(MS_FAILURE);
  }
  for(i=0; i<join->numitems; i++) {
    join->items[i] = (char *) malloc(8); /* plenty of space */
    sprintf(join->items[i], "%d", i+1);
  }

  return(MS_SUCCESS);
}

411
int msCSVJoinPrepare(joinObj *join, shapeObj *shape)
412 413 414 415
{
  msCSVJoinInfo *joininfo = join->joininfo;

  if(!joininfo) {
416
    msSetError(MS_JOINERR, "Join connection has not be created.", "msCSVJoinPrepare()");
417 418 419 420
    return(MS_FAILURE);
  }

  if(!shape) {
421
    msSetError(MS_JOINERR, "Shape to be joined is empty.", "msCSVJoinPrepare()");
422 423 424 425
    return(MS_FAILURE);
  }

  if(!shape->values) {
426
    msSetError(MS_JOINERR, "Shape to be joined has no attributes.", "msCSVJoinPrepare()");
427 428 429 430 431 432
    return(MS_FAILURE);
  }

  joininfo->nextrow = 0; /* starting with the first record */

  if(joininfo->target) free(joininfo->target); /* clear last target */
433
  joininfo->target = msStrdup(shape->values[joininfo->fromindex]);
434 435 436 437

  return(MS_SUCCESS);
}

438
int msCSVJoinNext(joinObj *join)
439 440 441 442 443
{
  int i,j;
  msCSVJoinInfo *joininfo = join->joininfo;

  if(!joininfo) {
444
    msSetError(MS_JOINERR, "Join connection has not be created.", "msCSVJoinNext()");
445 446 447 448
    return(MS_FAILURE);
  }

  /* clear any old data */
449
  if(join->values) {
450 451 452 453 454 455
    msFreeCharArray(join->values, join->numitems);
    join->values = NULL;
  }

  for(i=joininfo->nextrow; i<joininfo->numrows; i++) { /* find a match     */
    if(strcmp(joininfo->target, joininfo->rows[i][joininfo->toindex]) == 0) break;
456
  }
457 458 459 460 461

  if((join->values = (char ** )malloc(sizeof(char *)*join->numitems)) == NULL) {
    msSetError(MS_MEMERR, NULL, "msCSVJoinNext()");
    return(MS_FAILURE);
  }
462

463 464
  if(i == joininfo->numrows) { /* unable to do the join     */
    for(j=0; j<join->numitems; j++)
465
      join->values[j] = msStrdup("\0"); /* intialize to zero length strings */
466 467 468

    joininfo->nextrow = joininfo->numrows;
    return(MS_DONE);
469
  }
470 471

  for(j=0; j<join->numitems; j++)
472
    join->values[j] = msStrdup(joininfo->rows[i][j]);
473 474 475 476 477 478

  joininfo->nextrow = i+1; /* so we know where to start looking next time through */

  return(MS_SUCCESS);
}

479 480
int msCSVJoinClose(joinObj *join)
{
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
  int i;
  msCSVJoinInfo *joininfo = join->joininfo;

  if(!joininfo) return(MS_SUCCESS); /* already closed */

  for(i=0; i<joininfo->numrows; i++)
    msFreeCharArray(joininfo->rows[i], join->numitems);
  free(joininfo->rows);
  if(joininfo->target) free(joininfo->target);
  free(joininfo);
  joininfo = NULL;

  return(MS_SUCCESS);
}


497
#ifdef USE_MYSQL
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512

#ifndef _mysql_h
#include <mysql/mysql.h>
#endif

char* DB_HOST = NULL;
char* DB_USER = NULL;
char* DB_PASSWD = NULL;
char* DB_DATABASE = NULL;
char* delim;

#define MYDEBUG if (0)

MYSQL_RES *msMySQLQuery(char *q, MYSQL *conn)
{
513 514 515 516 517 518 519 520 521
  MYSQL_RES *qresult=NULL;
  if (mysql_query(conn,q) < 0) {
    mysql_close(conn);
    msSetError(MS_QUERYERR, "Bad mysql query (%s)", "msMySQLQuery()", q);
    return qresult;
  }
  if (!(qresult=mysql_store_result(conn)))    {
    mysql_close(conn);
    msSetError(MS_QUERYERR, "mysql query failed (%s)", "msMySQLQuery()", q);
522
    return qresult;
523 524
  }
  return qresult;
525 526 527 528 529 530 531
}

/*  */
/* mysql join functions */
/*  */
typedef struct {
  MYSQL mysql, *conn;
532 533 534
  MYSQL_RES *qresult;
  MYSQL_ROW row;
  int rows;
535
  int fromindex;
536
  char *tocolumn;
537 538 539 540 541 542
  char *target;
  int nextrecord;
} msMySQLJoinInfo;
#endif


543
int msMySQLJoinConnect(layerObj *layer, joinObj *join)
544
{
545

546 547
#ifndef USE_MYSQL
  msSetError(MS_QUERYERR, "MySQL support not available (compile with --with-mysql)", "msMySQLJoinConnect()");
548 549 550 551
  return(MS_FAILURE);
#else
  int i;
  char qbuf[4000];
552
  char *conn_decrypted;
553 554
  msMySQLJoinInfo *joininfo;

555 556 557
  MYDEBUG if (setvbuf(stdout, NULL, _IONBF , 0)) {
    printf("Whoops...");
  };
558
  if(join->joininfo) return(MS_SUCCESS); /* already open */
559

560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576
  /* allocate a msMySQLJoinInfo struct */
  joininfo = (msMySQLJoinInfo *) malloc(sizeof(msMySQLJoinInfo));
  if(!joininfo) {
    msSetError(MS_MEMERR, "Error allocating mysql table info structure.", "msMySQLJoinConnect()");
    return(MS_FAILURE);
  }

  /* initialize any members that won't get set later on in this function */
  joininfo->qresult = NULL;
  joininfo->target = NULL;
  joininfo->nextrecord = 0;

  join->joininfo = joininfo;

  /* open the mysql connection */

  if( join->connection == NULL ) {
577 578
    msSetError(MS_QUERYERR, "Error parsing MYSQL JOIN: nothing specified in CONNECTION statement.",
               "msMySQLJoinConnect()");
579

580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
    return(MS_FAILURE);
  }

  conn_decrypted = msDecryptStringTokens(layer->map, join->connection);
  if (conn_decrypted == NULL) {
    msSetError(MS_QUERYERR, "Error parsing MYSQL JOIN: unable to decrypt CONNECTION statement.",
               "msMySQLJoinConnect()");
    return(MS_FAILURE);
  }

  delim = msStrdup(":");
  DB_HOST = msStrdup(strtok(conn_decrypted, delim));
  DB_USER = msStrdup(strtok(NULL, delim));
  DB_PASSWD = msStrdup(strtok(NULL, delim));
  DB_DATABASE = msStrdup(strtok(NULL, delim));
  free(conn_decrypted);

  if (DB_HOST == NULL || DB_USER == NULL || DB_PASSWD == NULL || DB_DATABASE == NULL) {
    msSetError(MS_QUERYERR, "DB param error: at least one of HOST, USER, PASSWD or DATABASE is null!", "msMySQLJoinConnect()");
    return MS_FAILURE;
  }
  if (strcmp(DB_PASSWD, "none") == 0) strcpy(DB_PASSWD, "");
602 603

#if MYSQL_VERSION_ID >= 40000
604 605
  mysql_init(&(joininfo->mysql));
  if (!(joininfo->conn = mysql_real_connect(&(joininfo->mysql),DB_HOST,DB_USER,DB_PASSWD,NULL, 0, NULL, 0)))
606
#else
607
  if (!(joininfo->conn = mysql_connect(&(joininfo->mysql),DB_HOST,DB_USER,DB_PASSWD)))
608
#endif
609 610 611
  {
    char tmp[4000];
    snprintf( tmp, sizeof(tmp), "Failed to connect to SQL server: Error: %s\nHost: %s\nUsername:%s\nPassword:%s\n", mysql_error(joininfo->conn), DB_HOST, DB_USER, DB_PASSWD);
612 613
    msSetError(MS_QUERYERR, "%s",
               "msMYSQLLayerOpen()", tmp);
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636
    free(joininfo);
    return MS_FAILURE;
  }

  MYDEBUG printf("msMYSQLLayerOpen2 called<br>\n");
  if (mysql_select_db(joininfo->conn,DB_DATABASE) < 0) {
    mysql_close(joininfo->conn);
  }
  MYDEBUG printf("msMYSQLLayerOpen3 called<br>\n");
  if (joininfo->qresult != NULL) { /* query leftover */
    MYDEBUG printf("msMYSQLLayerOpen4 called<br>\n");
    mysql_free_result(joininfo->qresult);
  }
  MYDEBUG printf("msMYSQLLayerOpen5 called<br>\n");
  snprintf(qbuf, sizeof(qbuf), "SELECT count(%s) FROM %s", join->to, join->table);
  MYDEBUG printf("%s<br>\n", qbuf);
  if ((joininfo->qresult = msMySQLQuery(qbuf, joininfo->conn))) { /* There were some rows found, write 'em out for debug */
    int numrows = mysql_affected_rows(joininfo->conn);
    MYDEBUG printf("%d rows<br>\n", numrows);
    for(i=0; i<numrows; i++) {
      MYSQL_ROW row = mysql_fetch_row(joininfo->qresult);
      MYDEBUG printf("(%s)<BR>\n",row[0]);
      joininfo->rows = atoi(row[0]);
637
    }
638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660
  } else {
    msSetError(MS_DBFERR, "Item %s not found in table %s.", "msMySQLJoinConnect()", join->to, join->table);
    return(MS_FAILURE);
  }
  snprintf(qbuf, sizeof(qbuf), "EXPLAIN %s", join->table);
  if ((joininfo->qresult = msMySQLQuery(qbuf, joininfo->conn))) { /* There were some rows found, write 'em out for debug */
    join->numitems = mysql_affected_rows(joininfo->conn);
    if((join->items = (char **)malloc(sizeof(char *)*join->numitems)) == NULL) {
      msSetError(MS_MEMERR, NULL, "msMySQLJoinConnect()");
      return(MS_FAILURE);
    }
    MYDEBUG printf("%d rows<br>\n", join->numitems);
    for(i=0; i<join->numitems; i++) {
      MYSQL_ROW row = mysql_fetch_row(joininfo->qresult);
      MYDEBUG printf("(%s)<BR>\n",row[0]);
      join->items[i] = msStrdup(row[0]);
    }
  } else {
    msSetError(MS_DBFERR, "Item %s not found in table %s.", "msMySQLJoinConnect()", join->to, join->table);
    return(MS_FAILURE);
  }
  joininfo->tocolumn = msStrdup(join->to);

661 662 663 664 665 666 667 668 669 670 671


  /* get "from" item index   */
  for(i=0; i<layer->numitems; i++) {
    if(strcasecmp(layer->items[i],join->from) == 0) { /* found it */
      joininfo->fromindex = i;
      break;
    }
  }

  if(i == layer->numitems) {
672
    msSetError(MS_JOINERR, "Item %s not found in layer %s.", "msMySQLJoinConnect()", join->from, layer->name);
673 674 675 676
    return(MS_FAILURE);
  }

  /* finally store away the item names in the XBase table */
677
  if(!join->items) return(MS_FAILURE);
678 679 680 681 682

  return(MS_SUCCESS);
#endif
}

683
int msMySQLJoinPrepare(joinObj *join, shapeObj *shape)
684
{
685 686
#ifndef USE_MYSQL
  msSetError(MS_QUERYERR, "MySQL support not available (compile with --with-mysql)", "msMySQLJoinPrepare()");
687 688
  return(MS_FAILURE);
#else
689
  msMySQLJoinInfo *joininfo = join->joininfo;
690 691

  if(!joininfo) {
692
    msSetError(MS_JOINERR, "Join connection has not be created.", "msMySQLJoinPrepare()");
693 694 695 696
    return(MS_FAILURE);
  }

  if(!shape) {
697
    msSetError(MS_JOINERR, "Shape to be joined is empty.", "msMySQLJoinPrepare()");
698 699 700 701
    return(MS_FAILURE);
  }

  if(!shape->values) {
702
    msSetError(MS_JOINERR, "Shape to be joined has no attributes.", "msMySQLJoinPrepare()");
703 704 705 706 707 708
    return(MS_FAILURE);
  }

  joininfo->nextrecord = 0; /* starting with the first record */

  if(joininfo->target) free(joininfo->target); /* clear last target */
709
  joininfo->target = msStrdup(shape->values[joininfo->fromindex]);
710 711 712 713 714

  return(MS_SUCCESS);
#endif
}

715
int msMySQLJoinNext(joinObj *join)
716
{
717 718
#ifndef USE_MYSQL
  msSetError(MS_QUERYERR, "MySQL support not available (compile with --with-mysql)", "msMySQLJoinNext()");
719 720 721
  return(MS_FAILURE);
#else
  int i, n;
722
  char qbuf[4000];
723 724 725
  msMySQLJoinInfo *joininfo = join->joininfo;

  if(!joininfo) {
726
    msSetError(MS_JOINERR, "Join connection has not be created.", "msMySQLJoinNext()");
727 728 729 730 731 732 733 734 735
    return(MS_FAILURE);
  }

  if(!joininfo->target) {
    msSetError(MS_JOINERR, "No target specified, run msMySQLJoinPrepare() first.", "msMySQLJoinNext()");
    return(MS_FAILURE);
  }

  /* clear any old data */
736
  if(join->values) {
737 738 739 740 741
    msFreeCharArray(join->values, join->numitems);
    join->values = NULL;
  }

  n = joininfo->rows;
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

  /* for(i=joininfo->nextrecord; i<n; i++) { // find a match */
  /* if(strcmp(joininfo->target, msMySQLReadStringAttribute(joininfo->conn, i, joininfo->toindex)) == 0) break; */
  /* }   */
  snprintf(qbuf, sizeof(qbuf), "SELECT * FROM %s WHERE %s = %s", join->table, joininfo->tocolumn, joininfo->target);
  MYDEBUG printf("%s<BR>\n", qbuf);
  if ((joininfo->qresult = msMySQLQuery(qbuf, joininfo->conn))) { /* There were some rows found, write 'em out for debug */
    int numrows = mysql_affected_rows(joininfo->conn);
    int numfields = mysql_field_count(joininfo->conn);
    MYDEBUG printf("%d rows<br>\n", numrows);
    if (numrows > 0) {
      MYSQL_ROW row = mysql_fetch_row(joininfo->qresult);
      for(i=0; i<numfields; i++) {
        MYDEBUG printf("%s,",row[i]);
      }
      MYDEBUG printf("<BR>\n");
      free(join->values);
      if((join->values = (char **)malloc(sizeof(char *)*join->numitems)) == NULL) {
        msSetError(MS_MEMERR, NULL, "msMySQLJoinNext()");
        return(MS_FAILURE);
      }
      for(i=0; i<join->numitems; i++) {
        /* join->values[i] = msStrdup("\0"); */ /* intialize to zero length strings */
        join->values[i] = msStrdup(row[i]); /* intialize to zero length strings */
        /* rows = atoi(row[0]); */
      }
    } else {
      if((join->values = (char **)malloc(sizeof(char *)*join->numitems)) == NULL) {
        msSetError(MS_MEMERR, NULL, "msMySQLJoinNext()");
        return(MS_FAILURE);
      }
      for(i=0; i<join->numitems; i++)
        join->values[i] = msStrdup("\0"); /* intialize to zero length strings  */

      return(MS_DONE);
    }
  } else {
    msSetError(MS_QUERYERR, "Query error (%s)", "msMySQLJoinNext()", qbuf);
    return(MS_FAILURE);
  }
782 783 784 785 786 787 788 789

#ifdef __NOTDEF__
  if(i == n) { /* unable to do the join */
    if((join->values = (char **)malloc(sizeof(char *)*join->numitems)) == NULL) {
      msSetError(MS_MEMERR, NULL, "msMySQLJoinNext()");
      return(MS_FAILURE);
    }
    for(i=0; i<join->numitems; i++)
790
      join->values[i] = msStrdup("\0"); /* intialize to zero length strings  */
791 792 793 794

    joininfo->nextrecord = n;
    return(MS_DONE);
  }
795 796

  if((join->values = msMySQLGetValues(joininfo->conn,i)) == NULL)
797 798 799 800 801 802 803 804 805
    return(MS_FAILURE);

  joininfo->nextrecord = i+1; /* so we know where to start looking next time through */
#endif /* __NOTDEF__ */

  return(MS_SUCCESS);
#endif
}

806
int msMySQLJoinClose(joinObj *join)
807
{
808 809
#ifndef USE_MYSQL
  msSetError(MS_QUERYERR, "MySQL support not available (compile with --with-mysql)", "msMySQLJoinClose()");
810 811 812 813 814 815 816 817 818 819 820 821 822 823
  return(MS_FAILURE);
#else
  msMySQLJoinInfo *joininfo = join->joininfo;

  if(!joininfo) return(MS_SUCCESS); /* already closed */

  mysql_close(joininfo->conn);
  if(joininfo->target) free(joininfo->target);
  free(joininfo);
  joininfo = NULL;

  return(MS_SUCCESS);
#endif
}