LCOV - code coverage report
Current view: top level - ogr/ogrsf_frmts/csv - ogrcsvlayer.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 1206 1363 88.5 %
Date: 2025-03-29 15:49:56 Functions: 31 31 100.0 %

          Line data    Source code
       1             : /******************************************************************************
       2             :  *
       3             :  * Project:  CSV Translator
       4             :  * Purpose:  Implements OGRCSVLayer class.
       5             :  * Author:   Frank Warmerdam <warmerdam@pobox.com>
       6             :  *
       7             :  ******************************************************************************
       8             :  * Copyright (c) 2004, Frank Warmerdam <warmerdam@pobox.com>
       9             :  * Copyright (c) 2008-2014, Even Rouault <even dot rouault at spatialys.com>
      10             :  *
      11             :  * SPDX-License-Identifier: MIT
      12             :  ****************************************************************************/
      13             : 
      14             : #include "cpl_port.h"
      15             : #include "ogr_csv.h"
      16             : 
      17             : #include <cerrno>
      18             : #include <climits>
      19             : #include <cstddef>
      20             : #include <cstdio>
      21             : #include <cstdlib>
      22             : #include <cstring>
      23             : #if HAVE_FCNTL_H
      24             : #include <fcntl.h>
      25             : #endif
      26             : #include <algorithm>
      27             : #include <limits>
      28             : #include <string>
      29             : #include <vector>
      30             : 
      31             : #include "cpl_conv.h"
      32             : #include "cpl_csv.h"
      33             : #include "cpl_error.h"
      34             : #include "cpl_string.h"
      35             : #include "cpl_vsi.h"
      36             : #include "cpl_vsi_virtual.h"
      37             : #include "ogr_api.h"
      38             : #include "ogr_core.h"
      39             : #include "ogr_feature.h"
      40             : #include "ogr_geometry.h"
      41             : #include "ogr_p.h"
      42             : #include "ogr_spatialref.h"
      43             : #include "ogrsf_frmts.h"
      44             : 
      45             : #define DIGIT_ZERO '0'
      46             : 
      47             : /************************************************************************/
      48             : /*                            OGRCSVLayer()                             */
      49             : /*                                                                      */
      50             : /*      Note that the OGRCSVLayer assumes ownership of the passed       */
      51             : /*      file pointer.                                                   */
      52             : /************************************************************************/
      53             : 
      54         777 : OGRCSVLayer::OGRCSVLayer(GDALDataset *poDS, const char *pszLayerNameIn,
      55             :                          VSILFILE *fp, int nMaxLineSize,
      56             :                          const char *pszFilenameIn, int bNewIn,
      57         777 :                          int bInWriteModeIn, char chDelimiterIn)
      58             :     : m_poDS(poDS), poFeatureDefn(nullptr), fpCSV(fp),
      59             :       m_nMaxLineSize(nMaxLineSize), nNextFID(1), bHasFieldNames(false),
      60        1554 :       bNew(CPL_TO_BOOL(bNewIn)), bInWriteMode(CPL_TO_BOOL(bInWriteModeIn)),
      61             :       bUseCRLF(false), bNeedRewindBeforeRead(false),
      62        1554 :       eGeometryFormat(OGR_CSV_GEOM_NONE), pszFilename(CPLStrdup(pszFilenameIn)),
      63             :       bCreateCSVT(false), bWriteBOM(false), nCSVFieldCount(0),
      64             :       panGeomFieldIndex(nullptr), bFirstFeatureAppendedDuringSession(true),
      65             :       bHiddenWKTColumn(false), iNfdcLongitudeS(-1), iNfdcLatitudeS(-1),
      66             :       bHonourStrings(true), iLongitudeField(-1), iLatitudeField(-1),
      67             :       iZField(-1), bIsEurostatTSV(false), nEurostatDims(0),
      68         777 :       nTotalFeatures(bNewIn ? 0 : -1), bWarningBadTypeOrWidth(false),
      69             :       bKeepSourceColumns(false), bKeepGeomColumns(true), bMergeDelimiter(false),
      70         777 :       bEmptyStringNull(false)
      71             : {
      72         777 :     szDelimiter[0] = chDelimiterIn;
      73         777 :     szDelimiter[1] = 0;
      74         777 :     poFeatureDefn = new OGRFeatureDefn(pszLayerNameIn);
      75         777 :     SetDescription(poFeatureDefn->GetName());
      76         777 :     poFeatureDefn->Reference();
      77         777 :     poFeatureDefn->SetGeomType(wkbNone);
      78         777 : }
      79             : 
      80             : /************************************************************************/
      81             : /*                             Matches()                                */
      82             : /************************************************************************/
      83             : 
      84       10889 : bool OGRCSVLayer::Matches(const char *pszFieldName, char **papszPossibleNames)
      85             : {
      86       10889 :     if (papszPossibleNames == nullptr)
      87           0 :         return false;
      88       11001 :     for (char **papszIter = papszPossibleNames; *papszIter; papszIter++)
      89             :     {
      90         154 :         const char *pszPattern = *papszIter;
      91         154 :         const char *pszStar = strstr(pszPattern, "*");
      92         154 :         if (pszStar == nullptr)
      93             :         {
      94         145 :             if (EQUAL(pszFieldName, pszPattern))
      95          39 :                 return true;
      96             :         }
      97             :         else
      98             :         {
      99           9 :             if (pszStar == pszPattern)
     100             :             {
     101           6 :                 if (strlen(pszPattern) >= 3 &&
     102           6 :                     pszPattern[strlen(pszPattern) - 1] == '*')
     103             :                 {
     104             :                     // *pattern*
     105           3 :                     CPLString oPattern(pszPattern + 1);
     106           3 :                     oPattern.pop_back();
     107           3 :                     if (CPLString(pszFieldName).ifind(oPattern) !=
     108             :                         std::string::npos)
     109           3 :                         return true;
     110             :                 }
     111             :                 else
     112             :                 {
     113             :                     // *pattern
     114           3 :                     if (strlen(pszFieldName) >= strlen(pszPattern) - 1 &&
     115           1 :                         EQUAL(pszFieldName + strlen(pszFieldName) -
     116             :                                   (strlen(pszPattern) - 1),
     117             :                               pszPattern + 1))
     118             :                     {
     119           1 :                         return true;
     120             :                     }
     121             :                 }
     122             :             }
     123           3 :             else if (pszPattern[strlen(pszPattern) - 1] == '*')
     124             :             {
     125             :                 // pattern*
     126           3 :                 if (EQUALN(pszFieldName, pszPattern, strlen(pszPattern) - 1))
     127           1 :                     return true;
     128             :             }
     129             :         }
     130             :     }
     131       10847 :     return false;
     132             : }
     133             : 
     134             : /************************************************************************/
     135             : /*                      BuildFeatureDefn()                              */
     136             : /************************************************************************/
     137             : 
     138         777 : void OGRCSVLayer::BuildFeatureDefn(const char *pszNfdcGeomField,
     139             :                                    const char *pszGeonamesGeomFieldPrefix,
     140             :                                    CSLConstList papszOpenOptions)
     141             : {
     142         777 :     bMergeDelimiter = CPLFetchBool(papszOpenOptions, "MERGE_SEPARATOR", false);
     143         777 :     bEmptyStringNull =
     144         777 :         CPLFetchBool(papszOpenOptions, "EMPTY_STRING_AS_NULL", false);
     145             : 
     146             :     // If this is not a new file, read ahead to establish if it is
     147             :     // already in CRLF (DOS) mode, or just a normal unix CR mode.
     148         777 :     if (!bNew && bInWriteMode)
     149             :     {
     150          97 :         int nBytesRead = 0;
     151          97 :         char chNewByte = '\0';
     152             : 
     153       55787 :         while (nBytesRead < 10000 && VSIFReadL(&chNewByte, 1, 1, fpCSV) == 1)
     154             :         {
     155       55691 :             if (chNewByte == 13)
     156             :             {
     157           1 :                 bUseCRLF = true;
     158           1 :                 break;
     159             :             }
     160       55690 :             nBytesRead++;
     161             :         }
     162          97 :         VSIRewindL(fpCSV);
     163             :     }
     164             : 
     165             :     // Check if the first record seems to be field definitions or
     166             :     // not.  We assume it is field definitions if the HEADERS option
     167             :     // not supplied and none of the values are strictly numeric.
     168         777 :     char **papszTokens = nullptr;
     169         777 :     int nFieldCount = 0;
     170             : 
     171         777 :     if (!bNew)
     172             :     {
     173         645 :         const char *pszLine = CPLReadLineL(fpCSV);
     174         645 :         if (pszLine != nullptr)
     175             :         {
     176             :             // Detect and remove UTF-8 BOM marker if found (#4623).
     177         645 :             if (reinterpret_cast<const unsigned char *>(pszLine)[0] == 0xEF &&
     178           2 :                 reinterpret_cast<const unsigned char *>(pszLine)[1] == 0xBB &&
     179           2 :                 reinterpret_cast<const unsigned char *>(pszLine)[2] == 0xBF)
     180             :             {
     181           2 :                 pszLine += 3;
     182             :             }
     183             : 
     184             :             // Tokenize the strings and preserve quotes, so we can separate
     185             :             // string from numeric this is only used in the test for
     186             :             // bHasFieldNames (bug #4361).
     187             :             papszTokens =
     188         645 :                 CSLTokenizeString2(pszLine, szDelimiter,
     189             :                                    (CSLT_HONOURSTRINGS | CSLT_ALLOWEMPTYTOKENS |
     190             :                                     CSLT_PRESERVEQUOTES));
     191         645 :             nFieldCount = CSLCount(papszTokens);
     192             : 
     193         645 :             if (nFieldCount > 0 && papszTokens[0][0] == '"')
     194          29 :                 m_eStringQuoting = StringQuoting::ALWAYS;
     195             : 
     196             :             const char *pszCSVHeaders =
     197         645 :                 CSLFetchNameValueDef(papszOpenOptions, "HEADERS", "AUTO");
     198             : 
     199         645 :             if (EQUAL(pszCSVHeaders, "YES"))
     200             :             {
     201           0 :                 bHasFieldNames = true;
     202             :             }
     203         645 :             else if (EQUAL(pszCSVHeaders, "NO"))
     204             :             {
     205           0 :                 bHasFieldNames = false;
     206             :             }
     207             :             else
     208             :             {
     209             :                 // Detect via checking for the presence of numeric values.
     210         645 :                 bHasFieldNames = true;
     211        3476 :                 for (int iField = 0; iField < nFieldCount && bHasFieldNames;
     212             :                      iField++)
     213             :                 {
     214             :                     const CPLValueType eType =
     215        2831 :                         CPLGetValueType(papszTokens[iField]);
     216        2831 :                     if (eType == CPL_VALUE_INTEGER || eType == CPL_VALUE_REAL)
     217             :                     {
     218             :                         // We have a numeric field, therefore do not consider
     219             :                         // the first line as field names.
     220          66 :                         bHasFieldNames = false;
     221             :                     }
     222             :                 }
     223             : 
     224             :                 const CPLString osExt =
     225        1290 :                     OGRCSVDataSource::GetRealExtension(pszFilename);
     226             : 
     227             :                 // Eurostat .tsv files.
     228         646 :                 if (EQUAL(osExt, "tsv") && nFieldCount > 1 &&
     229         647 :                     strchr(papszTokens[0], ',') != nullptr &&
     230           1 :                     strchr(papszTokens[0], '\\') != nullptr)
     231             :                 {
     232           1 :                     bHasFieldNames = true;
     233           1 :                     bIsEurostatTSV = true;
     234             :                 }
     235             :             }
     236             : 
     237             :             // Tokenize without quotes to get the actual values.
     238         645 :             VSIRewindL(fpCSV);
     239         645 :             CSLDestroy(papszTokens);
     240             :             papszTokens =
     241        1290 :                 CSVReadParseLine3L(fpCSV, m_nMaxLineSize, szDelimiter,
     242             :                                    true,   // bHonourStrings
     243             :                                    false,  // bKeepLeadingAndClosingQuotes
     244         645 :                                    bMergeDelimiter,
     245             :                                    true  // bSkipBOM
     246             :                 );
     247         645 :             nFieldCount = CSLCount(papszTokens);
     248             :         }
     249             :     }
     250             :     else
     251             :     {
     252         132 :         bHasFieldNames = false;
     253             :     }
     254             : 
     255         777 :     if (!bNew)
     256         645 :         ResetReading();
     257             : 
     258             :     int nMaxFieldCount =
     259         777 :         atoi(CPLGetConfigOption("OGR_CSV_MAX_FIELD_COUNT", "2000"));
     260         777 :     if (nFieldCount > nMaxFieldCount)
     261             :     {
     262           0 :         CPLError(CE_Warning, CPLE_AppDefined,
     263             :                  "%d columns detected. Limiting to %d. "
     264             :                  "Set OGR_CSV_MAX_FIELD_COUNT configuration option "
     265             :                  "to allow more fields.",
     266             :                  nFieldCount, nMaxFieldCount);
     267           0 :         nFieldCount = nMaxFieldCount;
     268             :     }
     269         777 :     if (nFieldCount > 100000)
     270           0 :         nFieldCount = 100000;  // to please coverity
     271             : 
     272         777 :     nCSVFieldCount = nFieldCount;
     273             : 
     274             :     // coverity[tainted_data]
     275         777 :     panGeomFieldIndex = static_cast<int *>(CPLCalloc(nFieldCount, sizeof(int)));
     276        3932 :     for (int iField = 0; iField < nFieldCount; iField++)
     277             :     {
     278        3155 :         panGeomFieldIndex[iField] = -1;
     279             :     }
     280             : 
     281             :     // Check for geonames.org tables.
     282         777 :     if (!bHasFieldNames && nFieldCount == 19)
     283             :     {
     284           1 :         if (CPLGetValueType(papszTokens[0]) == CPL_VALUE_INTEGER &&
     285           1 :             CPLGetValueType(papszTokens[4]) == CPL_VALUE_REAL &&
     286           1 :             CPLGetValueType(papszTokens[5]) == CPL_VALUE_REAL &&
     287           1 :             CPLAtof(papszTokens[4]) >= -90 && CPLAtof(papszTokens[4]) <= 90 &&
     288           2 :             CPLAtof(papszTokens[5]) >= -180 && CPLAtof(papszTokens[4]) <= 180)
     289             :         {
     290           1 :             CSLDestroy(papszTokens);
     291           1 :             papszTokens = nullptr;
     292             : 
     293             :             static const struct
     294             :             {
     295             :                 const char *pszName;
     296             :                 OGRFieldType eType;
     297             :             } asGeonamesFieldDesc[] = {
     298             :                 {"GEONAMEID", OFTString}, {"NAME", OFTString},
     299             :                 {"ASCIINAME", OFTString}, {"ALTNAMES", OFTString},
     300             :                 {"LATITUDE", OFTReal},    {"LONGITUDE", OFTReal},
     301             :                 {"FEATCLASS", OFTString}, {"FEATCODE", OFTString},
     302             :                 {"COUNTRY", OFTString},   {"CC2", OFTString},
     303             :                 {"ADMIN1", OFTString},    {"ADMIN2", OFTString},
     304             :                 {"ADMIN3", OFTString},    {"ADMIN4", OFTString},
     305             :                 {"POPULATION", OFTReal},  {"ELEVATION", OFTInteger},
     306             :                 {"GTOPO30", OFTInteger},  {"TIMEZONE", OFTString},
     307             :                 {"MODDATE", OFTString}};
     308             : 
     309          20 :             for (int iField = 0; iField < nFieldCount; iField++)
     310             :             {
     311          19 :                 OGRFieldDefn oFieldDefn(asGeonamesFieldDesc[iField].pszName,
     312          38 :                                         asGeonamesFieldDesc[iField].eType);
     313          19 :                 poFeatureDefn->AddFieldDefn(&oFieldDefn);
     314             :             }
     315             : 
     316           1 :             iLatitudeField = 4;
     317           1 :             iLongitudeField = 5;
     318             : 
     319           1 :             nFieldCount = 0;
     320             : 
     321           1 :             bHonourStrings = false;
     322             :         }
     323             :     }
     324             : 
     325             :     // Search a csvt file for types.
     326         777 :     char **papszFieldTypes = nullptr;
     327         777 :     if (!bNew)
     328             :     {
     329             :         // Only try to read .csvt from files that have an extension
     330         645 :         if (!CPLGetExtensionSafe(pszFilename).empty())
     331             :         {
     332             :             const std::string osCSVTFilename =
     333        1290 :                 CPLResetExtensionSafe(pszFilename, "csvt");
     334         645 :             VSILFILE *fpCSVT = VSIFOpenL(osCSVTFilename.c_str(), "r");
     335         645 :             if (fpCSVT != nullptr)
     336             :             {
     337         127 :                 m_osCSVTFilename = osCSVTFilename;
     338         127 :                 VSIRewindL(fpCSVT);
     339             :                 papszFieldTypes =
     340         127 :                     CSVReadParseLine3L(fpCSVT, m_nMaxLineSize, ",",
     341             :                                        true,   // bHonourStrings
     342             :                                        false,  // bKeepLeadingAndClosingQuotes
     343             :                                        false,  // bMergeDelimiter,
     344             :                                        true    // bSkipBOM
     345             :                     );
     346         127 :                 VSIFCloseL(fpCSVT);
     347             :             }
     348             :         }
     349             :     }
     350             : 
     351             :     // Optionally auto-detect types.
     352        1295 :     if (!bNew && papszFieldTypes == nullptr &&
     353         518 :         CPLTestBool(
     354             :             CSLFetchNameValueDef(papszOpenOptions, "AUTODETECT_TYPE", "NO")))
     355             :     {
     356          25 :         papszFieldTypes = AutodetectFieldTypes(papszOpenOptions, nFieldCount);
     357          25 :         if (papszFieldTypes != nullptr)
     358             :         {
     359          25 :             bKeepSourceColumns = CPLTestBool(CSLFetchNameValueDef(
     360             :                 papszOpenOptions, "KEEP_SOURCE_COLUMNS", "NO"));
     361             :         }
     362             :     }
     363             : 
     364         777 :     char **papszGeomPossibleNames = CSLTokenizeString2(
     365             :         CSLFetchNameValue(papszOpenOptions, "GEOM_POSSIBLE_NAMES"), ",", 0);
     366         777 :     char **papszXPossibleNames = CSLTokenizeString2(
     367             :         CSLFetchNameValue(papszOpenOptions, "X_POSSIBLE_NAMES"), ",", 0);
     368         777 :     char **papszYPossibleNames = CSLTokenizeString2(
     369             :         CSLFetchNameValue(papszOpenOptions, "Y_POSSIBLE_NAMES"), ",", 0);
     370         777 :     char **papszZPossibleNames = CSLTokenizeString2(
     371             :         CSLFetchNameValue(papszOpenOptions, "Z_POSSIBLE_NAMES"), ",", 0);
     372         777 :     bKeepGeomColumns = CPLTestBool(
     373             :         CSLFetchNameValueDef(papszOpenOptions, "KEEP_GEOM_COLUMNS", "YES"));
     374             : 
     375             :     // Build field definitions.
     376         777 :     poFeatureDefn->ReserveSpaceForFields(nFieldCount);
     377             : 
     378         777 :     constexpr int knMAX_GEOM_COLUMNS = 100;
     379         777 :     bool bWarnedMaxGeomFields = false;
     380             : 
     381         777 :     const int nFieldTypesCount = CSLCount(papszFieldTypes);
     382             : 
     383        3909 :     for (int iField = 0; !bIsEurostatTSV && iField < nFieldCount; iField++)
     384             :     {
     385        3132 :         char *pszFieldName = nullptr;
     386             :         char szFieldNameBuffer[100];
     387             : 
     388        3132 :         if (bHasFieldNames)
     389             :         {
     390        2702 :             pszFieldName = papszTokens[iField];
     391             : 
     392             :             // Trim white space.
     393        2710 :             while (*pszFieldName == ' ')
     394           8 :                 pszFieldName++;
     395             : 
     396        2710 :             while (pszFieldName[0] != '\0' &&
     397        2710 :                    pszFieldName[strlen(pszFieldName) - 1] == ' ')
     398           8 :                 pszFieldName[strlen(pszFieldName) - 1] = '\0';
     399             : 
     400        2702 :             if (*pszFieldName == '\0')
     401           0 :                 pszFieldName = nullptr;
     402             :         }
     403             : 
     404        3132 :         if (pszFieldName == nullptr)
     405             :         {
     406             :             // Re-read single column CSV files that have a trailing comma
     407             :             // in the header line.
     408         430 :             if (iField == 1 && nFieldCount == 2 && papszTokens[1][0] == '\0')
     409             :             {
     410           0 :                 nCSVFieldCount = 1;
     411           0 :                 nFieldCount = 1;
     412           0 :                 break;
     413             :             }
     414         430 :             pszFieldName = szFieldNameBuffer;
     415         430 :             snprintf(szFieldNameBuffer, sizeof(szFieldNameBuffer), "field_%d",
     416             :                      iField + 1);
     417             :         }
     418             : 
     419        3132 :         OGRFieldDefn oField(pszFieldName, OFTString);
     420        3132 :         if (papszFieldTypes != nullptr && iField < nFieldTypesCount)
     421             :         {
     422         929 :             if (EQUAL(papszFieldTypes[iField], "WKT"))
     423             :             {
     424          14 :                 if (bKeepGeomColumns)
     425          14 :                     poFeatureDefn->AddFieldDefn(&oField);
     426             : 
     427          14 :                 if (poFeatureDefn->GetGeomFieldCount() == knMAX_GEOM_COLUMNS)
     428             :                 {
     429           0 :                     if (!bWarnedMaxGeomFields)
     430             :                     {
     431           0 :                         CPLError(CE_Warning, CPLE_NotSupported,
     432             :                                  "A maximum number of %d geometry fields is "
     433             :                                  "supported. "
     434             :                                  "Only the first ones are taken into account.",
     435             :                                  knMAX_GEOM_COLUMNS);
     436           0 :                         bWarnedMaxGeomFields = true;
     437             :                     }
     438           0 :                     continue;
     439             :                 }
     440             : 
     441          14 :                 eGeometryFormat = OGR_CSV_GEOM_AS_WKT;
     442          14 :                 panGeomFieldIndex[iField] = poFeatureDefn->GetGeomFieldCount();
     443          28 :                 std::string osGeomColName;
     444          14 :                 if (bKeepGeomColumns)
     445          14 :                     osGeomColName += "geom_";
     446          14 :                 osGeomColName += oField.GetNameRef();
     447             :                 OGRGeomFieldDefn oGeomFieldDefn(osGeomColName.c_str(),
     448          28 :                                                 wkbUnknown);
     449          14 :                 poFeatureDefn->AddGeomFieldDefn(&oGeomFieldDefn);
     450          14 :                 continue;
     451             :             }
     452         915 :             else if (EQUAL(papszFieldTypes[iField], "CoordX") ||
     453         911 :                      EQUAL(papszFieldTypes[iField], "Point(X)"))
     454             :             {
     455           4 :                 oField.SetType(OFTReal);
     456           4 :                 iLongitudeField = iField;
     457           4 :                 osXField = oField.GetNameRef();
     458           4 :                 if (bKeepGeomColumns)
     459           4 :                     poFeatureDefn->AddFieldDefn(&oField);
     460           4 :                 continue;
     461             :             }
     462         911 :             else if (EQUAL(papszFieldTypes[iField], "CoordY") ||
     463         907 :                      EQUAL(papszFieldTypes[iField], "Point(Y)"))
     464             :             {
     465           4 :                 oField.SetType(OFTReal);
     466           4 :                 iLatitudeField = iField;
     467           4 :                 osYField = oField.GetNameRef();
     468           4 :                 if (bKeepGeomColumns)
     469           4 :                     poFeatureDefn->AddFieldDefn(&oField);
     470           4 :                 continue;
     471             :             }
     472         907 :             else if (EQUAL(papszFieldTypes[iField], "CoordZ") ||
     473         907 :                      EQUAL(papszFieldTypes[iField], "Point(Z)"))
     474             :             {
     475           0 :                 oField.SetType(OFTReal);
     476           0 :                 iZField = iField;
     477           0 :                 osZField = oField.GetNameRef();
     478           0 :                 if (bKeepGeomColumns)
     479           0 :                     poFeatureDefn->AddFieldDefn(&oField);
     480           0 :                 continue;
     481             :             }
     482         907 :             else if (EQUAL(papszFieldTypes[iField], "Integer(Boolean)"))
     483             :             {
     484          13 :                 oField.SetType(OFTInteger);
     485          13 :                 oField.SetSubType(OFSTBoolean);
     486          13 :                 oField.SetWidth(1);
     487             :             }
     488         894 :             else if (EQUAL(papszFieldTypes[iField], "Integer(Int16)"))
     489             :             {
     490           1 :                 oField.SetType(OFTInteger);
     491           1 :                 oField.SetSubType(OFSTInt16);
     492             :             }
     493         893 :             else if (EQUAL(papszFieldTypes[iField], "Real(Float32)"))
     494             :             {
     495           1 :                 oField.SetType(OFTReal);
     496           1 :                 oField.SetSubType(OFSTFloat32);
     497             :             }
     498             :             else
     499             :             {
     500         892 :                 char *pszLeftParenthesis = strchr(papszFieldTypes[iField], '(');
     501         892 :                 if (pszLeftParenthesis &&
     502         143 :                     pszLeftParenthesis != papszFieldTypes[iField] &&
     503         143 :                     pszLeftParenthesis[1] >= '0' &&
     504         143 :                     pszLeftParenthesis[1] <= '9')
     505             :                 {
     506         143 :                     char *pszDot = strchr(pszLeftParenthesis, '.');
     507         143 :                     if (pszDot)
     508          41 :                         *pszDot = 0;
     509         143 :                     *pszLeftParenthesis = 0;
     510             : 
     511         143 :                     if (pszLeftParenthesis[-1] == ' ')
     512         119 :                         pszLeftParenthesis[-1] = 0;
     513             : 
     514         143 :                     const int nWidth = atoi(pszLeftParenthesis + 1);
     515         143 :                     const int nPrecision = pszDot ? atoi(pszDot + 1) : 0;
     516             : 
     517         143 :                     oField.SetWidth(nWidth);
     518         143 :                     oField.SetPrecision(nPrecision);
     519             :                 }
     520             : 
     521         892 :                 if (EQUAL(papszFieldTypes[iField], "Integer"))
     522          85 :                     oField.SetType(OFTInteger);
     523         807 :                 else if (EQUAL(papszFieldTypes[iField], "Integer64"))
     524           9 :                     oField.SetType(OFTInteger64);
     525         798 :                 else if (EQUAL(papszFieldTypes[iField], "Real"))
     526         221 :                     oField.SetType(OFTReal);
     527         577 :                 else if (EQUAL(papszFieldTypes[iField], "String"))
     528         462 :                     oField.SetType(OFTString);
     529         115 :                 else if (EQUAL(papszFieldTypes[iField], "Date"))
     530          24 :                     oField.SetType(OFTDate);
     531          91 :                 else if (EQUAL(papszFieldTypes[iField], "Time"))
     532          21 :                     oField.SetType(OFTTime);
     533          70 :                 else if (EQUAL(papszFieldTypes[iField], "DateTime"))
     534          61 :                     oField.SetType(OFTDateTime);
     535           9 :                 else if (EQUAL(papszFieldTypes[iField], "JSonStringList"))
     536           3 :                     oField.SetType(OFTStringList);
     537           6 :                 else if (EQUAL(papszFieldTypes[iField], "JSonIntegerList"))
     538           2 :                     oField.SetType(OFTIntegerList);
     539           4 :                 else if (EQUAL(papszFieldTypes[iField], "JSonInteger64List"))
     540           2 :                     oField.SetType(OFTInteger64List);
     541           2 :                 else if (EQUAL(papszFieldTypes[iField], "JSonRealList"))
     542           2 :                     oField.SetType(OFTRealList);
     543             :                 else
     544           0 :                     CPLError(CE_Warning, CPLE_NotSupported, "Unknown type : %s",
     545           0 :                              papszFieldTypes[iField]);
     546             :             }
     547             :         }
     548             : 
     549        3110 :         if (Matches(oField.GetNameRef(), papszZPossibleNames))
     550             :         {
     551           4 :             oField.SetType(OFTReal);
     552           4 :             iZField = iField;
     553           4 :             osZField = oField.GetNameRef();
     554           4 :             if (!bKeepGeomColumns)
     555           2 :                 continue;
     556             :         }
     557        3106 :         else if ((iNfdcLatitudeS != -1 && iNfdcLongitudeS != -1) ||
     558        3106 :                  (iLatitudeField != -1 && iLongitudeField != -1))
     559             :         {
     560             :             // Do nothing.
     561             :         }
     562        3093 :         else if ((EQUAL(oField.GetNameRef(), "WKT") ||
     563        3581 :                   STARTS_WITH_CI(oField.GetNameRef(), "_WKT")) &&
     564         488 :                  oField.GetType() == OFTString)
     565             :         {
     566         488 :             if (poFeatureDefn->GetGeomFieldCount() == knMAX_GEOM_COLUMNS)
     567             :             {
     568           1 :                 if (!bWarnedMaxGeomFields)
     569             :                 {
     570           1 :                     CPLError(
     571             :                         CE_Warning, CPLE_NotSupported,
     572             :                         "A maximum number of %d geometry fields is supported. "
     573             :                         "Only the first ones are taken into account.",
     574             :                         knMAX_GEOM_COLUMNS);
     575           1 :                     bWarnedMaxGeomFields = true;
     576             :                 }
     577             :             }
     578             :             else
     579             :             {
     580         487 :                 eGeometryFormat = OGR_CSV_GEOM_AS_WKT;
     581             : 
     582         487 :                 panGeomFieldIndex[iField] = poFeatureDefn->GetGeomFieldCount();
     583             :                 OGRGeomFieldDefn oGeomFieldDefn(
     584         487 :                     EQUAL(pszFieldName, "WKT")
     585             :                         ? ""
     586         247 :                         : CPLSPrintf("geom_%s", pszFieldName),
     587         734 :                     wkbUnknown);
     588             : 
     589             :                 // Useful hack for RFC 41 testing.
     590         487 :                 const char *pszEPSG = strstr(pszFieldName, "_EPSG_");
     591         487 :                 if (pszEPSG != nullptr)
     592             :                 {
     593         242 :                     const int nEPSGCode = atoi(pszEPSG + strlen("_EPSG_"));
     594         242 :                     OGRSpatialReference *poSRS = new OGRSpatialReference();
     595         242 :                     poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
     596         242 :                     poSRS->importFromEPSG(nEPSGCode);
     597         242 :                     oGeomFieldDefn.SetSpatialRef(poSRS);
     598         242 :                     poSRS->Release();
     599             :                 }
     600             : 
     601         487 :                 if (strstr(pszFieldName, "_POINT"))
     602         102 :                     oGeomFieldDefn.SetType(wkbPoint);
     603         385 :                 else if (strstr(pszFieldName, "_LINESTRING"))
     604          34 :                     oGeomFieldDefn.SetType(wkbLineString);
     605         351 :                 else if (strstr(pszFieldName, "_POLYGON"))
     606          68 :                     oGeomFieldDefn.SetType(wkbPolygon);
     607         283 :                 else if (strstr(pszFieldName, "_MULTIPOINT"))
     608           0 :                     oGeomFieldDefn.SetType(wkbMultiPoint);
     609         283 :                 else if (strstr(pszFieldName, "_MULTILINESTRING"))
     610           0 :                     oGeomFieldDefn.SetType(wkbMultiLineString);
     611         283 :                 else if (strstr(pszFieldName, "_MULTIPOLYGON"))
     612           0 :                     oGeomFieldDefn.SetType(wkbMultiPolygon);
     613         283 :                 else if (strstr(pszFieldName, "_CIRCULARSTRING"))
     614           0 :                     oGeomFieldDefn.SetType(wkbCircularString);
     615         283 :                 else if (strstr(pszFieldName, "_COMPOUNDCURVE"))
     616           0 :                     oGeomFieldDefn.SetType(wkbCompoundCurve);
     617         283 :                 else if (strstr(pszFieldName, "_CURVEPOLYGON"))
     618           4 :                     oGeomFieldDefn.SetType(wkbCurvePolygon);
     619         279 :                 else if (strstr(pszFieldName, "_CURVE"))
     620           0 :                     oGeomFieldDefn.SetType(wkbCurve);
     621         279 :                 else if (strstr(pszFieldName, "_SURFACE"))
     622           0 :                     oGeomFieldDefn.SetType(wkbSurface);
     623         279 :                 else if (strstr(pszFieldName, "_MULTICURVE"))
     624           0 :                     oGeomFieldDefn.SetType(wkbMultiCurve);
     625         279 :                 else if (strstr(pszFieldName, "_MULTISURFACE"))
     626           0 :                     oGeomFieldDefn.SetType(wkbMultiSurface);
     627         279 :                 else if (strstr(pszFieldName, "_POLYHEDRALSURFACE"))
     628           0 :                     oGeomFieldDefn.SetType(wkbPolyhedralSurface);
     629         279 :                 else if (strstr(pszFieldName, "_TIN"))
     630           0 :                     oGeomFieldDefn.SetType(wkbTIN);
     631         279 :                 else if (strstr(pszFieldName, "_TRIANGLE"))
     632           0 :                     oGeomFieldDefn.SetType(wkbTriangle);
     633             : 
     634         487 :                 poFeatureDefn->AddGeomFieldDefn(&oGeomFieldDefn);
     635         487 :                 if (!bKeepGeomColumns)
     636           0 :                     continue;
     637             :             }
     638             :         }
     639        2605 :         else if (Matches(oField.GetNameRef(), papszGeomPossibleNames))
     640             :         {
     641          12 :             eGeometryFormat = OGR_CSV_GEOM_AS_SOME_GEOM_FORMAT;
     642          12 :             panGeomFieldIndex[iField] = poFeatureDefn->GetGeomFieldCount();
     643          12 :             OGRGeomFieldDefn oGeomFieldDefn(oField.GetNameRef(), wkbUnknown);
     644          12 :             poFeatureDefn->AddGeomFieldDefn(&oGeomFieldDefn);
     645          12 :             if (!bKeepGeomColumns)
     646           7 :                 continue;
     647             :         }
     648        2606 :         else if (Matches(oField.GetNameRef(), papszXPossibleNames) &&
     649          13 :                  poFeatureDefn->GetGeomFieldCount() == 0)
     650             :         {
     651          12 :             oField.SetType(OFTReal);
     652          12 :             iLongitudeField = iField;
     653          12 :             osXField = oField.GetNameRef();
     654          12 :             if (!bKeepGeomColumns)
     655           6 :                 continue;
     656             :         }
     657        2594 :         else if (Matches(oField.GetNameRef(), papszYPossibleNames) &&
     658          13 :                  poFeatureDefn->GetGeomFieldCount() == 0)
     659             :         {
     660          12 :             oField.SetType(OFTReal);
     661          12 :             iLatitudeField = iField;
     662          12 :             osYField = oField.GetNameRef();
     663          12 :             if (!bKeepGeomColumns)
     664           6 :                 continue;
     665             :         }
     666             : 
     667             :         // TODO(schwehr): URL broken.
     668             :         // http://www.faa.gov/airports/airport_safety/airportdata_5010/menu/index.cfm
     669             :         // specific
     670        2569 :         else if (pszNfdcGeomField != nullptr &&
     671           0 :                  EQUALN(oField.GetNameRef(), pszNfdcGeomField,
     672           0 :                         strlen(pszNfdcGeomField)) &&
     673           0 :                  EQUAL(oField.GetNameRef() + strlen(pszNfdcGeomField),
     674        2569 :                        "LatitudeS") &&
     675           0 :                  poFeatureDefn->GetGeomFieldCount() == 0)
     676             :         {
     677           0 :             iNfdcLatitudeS = iField;
     678           0 :             if (!bKeepGeomColumns)
     679           0 :                 continue;
     680             :         }
     681        2569 :         else if (pszNfdcGeomField != nullptr &&
     682           0 :                  EQUALN(oField.GetNameRef(), pszNfdcGeomField,
     683           0 :                         strlen(pszNfdcGeomField)) &&
     684           0 :                  EQUAL(oField.GetNameRef() + strlen(pszNfdcGeomField),
     685        2569 :                        "LongitudeS") &&
     686           0 :                  poFeatureDefn->GetGeomFieldCount() == 0)
     687             :         {
     688           0 :             iNfdcLongitudeS = iField;
     689           0 :             if (!bKeepGeomColumns)
     690           0 :                 continue;
     691             :         }
     692             :         // GNIS specific.
     693        2569 :         else if (pszGeonamesGeomFieldPrefix != nullptr &&
     694           0 :                  EQUALN(oField.GetNameRef(), pszGeonamesGeomFieldPrefix,
     695           0 :                         strlen(pszGeonamesGeomFieldPrefix)) &&
     696           0 :                  (EQUAL(oField.GetNameRef() +
     697             :                             strlen(pszGeonamesGeomFieldPrefix),
     698           0 :                         "_LAT_DEC") ||
     699           0 :                   EQUAL(oField.GetNameRef() +
     700             :                             strlen(pszGeonamesGeomFieldPrefix),
     701           0 :                         "_LATITUDE_DEC") ||
     702           0 :                   EQUAL(oField.GetNameRef() +
     703             :                             strlen(pszGeonamesGeomFieldPrefix),
     704        2569 :                         "_LATITUDE")) &&
     705           0 :                  poFeatureDefn->GetGeomFieldCount() == 0)
     706             :         {
     707           0 :             m_bIsGNIS = true;
     708           0 :             oField.SetType(OFTReal);
     709           0 :             iLatitudeField = iField;
     710           0 :             osYField = oField.GetNameRef();
     711           0 :             if (!bKeepGeomColumns)
     712           0 :                 continue;
     713             :         }
     714        2569 :         else if (pszGeonamesGeomFieldPrefix != nullptr &&
     715           0 :                  EQUALN(oField.GetNameRef(), pszGeonamesGeomFieldPrefix,
     716           0 :                         strlen(pszGeonamesGeomFieldPrefix)) &&
     717           0 :                  (EQUAL(oField.GetNameRef() +
     718             :                             strlen(pszGeonamesGeomFieldPrefix),
     719           0 :                         "_LONG_DEC") ||
     720           0 :                   EQUAL(oField.GetNameRef() +
     721             :                             strlen(pszGeonamesGeomFieldPrefix),
     722           0 :                         "_LONGITUDE_DEC") ||
     723           0 :                   EQUAL(oField.GetNameRef() +
     724             :                             strlen(pszGeonamesGeomFieldPrefix),
     725        2569 :                         "_LONGITUDE")) &&
     726           0 :                  poFeatureDefn->GetGeomFieldCount() == 0)
     727             :         {
     728           0 :             m_bIsGNIS = true;
     729           0 :             oField.SetType(OFTReal);
     730           0 :             iLongitudeField = iField;
     731           0 :             osXField = oField.GetNameRef();
     732           0 :             if (!bKeepGeomColumns)
     733           0 :                 continue;
     734             :         }
     735             : 
     736        3089 :         poFeatureDefn->AddFieldDefn(&oField);
     737             : 
     738        3089 :         if (bKeepSourceColumns && oField.GetType() != OFTString)
     739             :         {
     740             :             OGRFieldDefn oFieldOriginal(
     741          22 :                 CPLSPrintf("%s_original", oField.GetNameRef()), OFTString);
     742          11 :             poFeatureDefn->AddFieldDefn(&oFieldOriginal);
     743             :         }
     744             :     }
     745             : 
     746         777 :     if (iNfdcLatitudeS != -1 && iNfdcLongitudeS != -1)
     747             :     {
     748           0 :         bHonourStrings = false;
     749           0 :         if (poFeatureDefn->GetGeomFieldCount() == 0)
     750             :         {
     751           0 :             poFeatureDefn->SetGeomType(wkbPoint);
     752             :         }
     753             :         else
     754             :         {
     755           0 :             iNfdcLatitudeS = -1;
     756           0 :             iNfdcLongitudeS = -1;
     757           0 :             iLatitudeField = -1;
     758           0 :             iLongitudeField = -1;
     759             :         }
     760             :     }
     761         777 :     else if (iLatitudeField != -1 && iLongitudeField != -1)
     762             :     {
     763          17 :         if (poFeatureDefn->GetGeomFieldCount() == 0)
     764             :         {
     765          17 :             poFeatureDefn->SetGeomType(iZField >= 0 ? wkbPoint25D : wkbPoint);
     766             :         }
     767             :         else
     768             :         {
     769           0 :             iNfdcLatitudeS = -1;
     770           0 :             iNfdcLongitudeS = -1;
     771           0 :             iLatitudeField = -1;
     772           0 :             iLongitudeField = -1;
     773             :         }
     774             :     }
     775             : 
     776        1048 :     if (poFeatureDefn->GetGeomFieldCount() > 0 &&
     777         271 :         poFeatureDefn->GetGeomFieldDefn(0)->GetSpatialRef() == nullptr)
     778             :     {
     779             :         VSILFILE *fpPRJ =
     780         182 :             VSIFOpenL(CPLResetExtensionSafe(pszFilename, "prj").c_str(), "rb");
     781         182 :         if (fpPRJ != nullptr)
     782             :         {
     783           2 :             GByte *pabyRet = nullptr;
     784           2 :             if (VSIIngestFile(fpPRJ, nullptr, &pabyRet, nullptr, 1000000))
     785             :             {
     786           2 :                 OGRSpatialReference *poSRS = new OGRSpatialReference();
     787           2 :                 poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
     788           2 :                 if (poSRS->SetFromUserInput(
     789             :                         (const char *)pabyRet,
     790             :                         OGRSpatialReference::
     791           2 :                             SET_FROM_USER_INPUT_LIMITATIONS_get()) ==
     792             :                     OGRERR_NONE)
     793             :                 {
     794           2 :                     poFeatureDefn->GetGeomFieldDefn(0)->SetSpatialRef(poSRS);
     795             :                 }
     796           2 :                 poSRS->Release();
     797             :             }
     798           2 :             CPLFree(pabyRet);
     799           2 :             VSIFCloseL(fpPRJ);
     800             :         }
     801             :     }
     802             : 
     803         777 :     CSLDestroy(papszGeomPossibleNames);
     804         777 :     CSLDestroy(papszXPossibleNames);
     805         777 :     CSLDestroy(papszYPossibleNames);
     806         777 :     CSLDestroy(papszZPossibleNames);
     807             : 
     808             :     // Build field definitions for Eurostat TSV files.
     809             : 
     810        1554 :     CPLString osSeqDim;
     811         781 :     for (int iField = 0; bIsEurostatTSV && iField < nFieldCount; iField++)
     812             :     {
     813           4 :         if (iField == 0)
     814             :         {
     815           1 :             char **papszDims = CSLTokenizeString2(papszTokens[0], ",\\", 0);
     816           1 :             nEurostatDims = CSLCount(papszDims) - 1;
     817           3 :             for (int iSubField = 0; iSubField < nEurostatDims; iSubField++)
     818             :             {
     819           4 :                 OGRFieldDefn oField(papszDims[iSubField], OFTString);
     820           2 :                 poFeatureDefn->AddFieldDefn(&oField);
     821             :             }
     822             : 
     823           1 :             if (nEurostatDims >= 0)
     824           1 :                 osSeqDim = papszDims[nEurostatDims];
     825             :             else
     826           0 :                 CPLError(CE_Warning, CPLE_AppDefined, "Invalid nEurostatDims");
     827             : 
     828           1 :             CSLDestroy(papszDims);
     829             :         }
     830             :         else
     831             :         {
     832           3 :             if (papszTokens[iField][0] != '\0' &&
     833           3 :                 papszTokens[iField][strlen(papszTokens[iField]) - 1] == ' ')
     834           3 :                 papszTokens[iField][strlen(papszTokens[iField]) - 1] = '\0';
     835             : 
     836             :             OGRFieldDefn oField(
     837           3 :                 CPLSPrintf("%s_%s", osSeqDim.c_str(), papszTokens[iField]),
     838           6 :                 OFTReal);
     839           3 :             poFeatureDefn->AddFieldDefn(&oField);
     840             : 
     841             :             OGRFieldDefn oField2(
     842           3 :                 CPLSPrintf("%s_%s_flag", osSeqDim.c_str(), papszTokens[iField]),
     843           6 :                 OFTString);
     844           3 :             poFeatureDefn->AddFieldDefn(&oField2);
     845             :         }
     846             :     }
     847             : 
     848         777 :     CSLDestroy(papszTokens);
     849         777 :     CSLDestroy(papszFieldTypes);
     850         777 : }
     851             : 
     852             : /************************************************************************/
     853             : /*                             GetFileList()                            */
     854             : /************************************************************************/
     855             : 
     856          29 : std::vector<std::string> OGRCSVLayer::GetFileList()
     857             : {
     858          29 :     std::vector<std::string> ret;
     859          29 :     ret.emplace_back(pszFilename);
     860          29 :     if (!m_osCSVTFilename.empty())
     861          11 :         ret.emplace_back(m_osCSVTFilename);
     862          29 :     return ret;
     863             : }
     864             : 
     865             : /************************************************************************/
     866             : /*                             OGRCSVIsTrue()                           */
     867             : /************************************************************************/
     868             : 
     869         193 : static bool OGRCSVIsTrue(const char *pszStr)
     870             : {
     871         190 :     return EQUAL(pszStr, "t") || EQUAL(pszStr, "true") || EQUAL(pszStr, "y") ||
     872         383 :            EQUAL(pszStr, "yes") || EQUAL(pszStr, "on");
     873             : }
     874             : 
     875             : /************************************************************************/
     876             : /*                            OGRCSVIsFalse()                           */
     877             : /************************************************************************/
     878             : 
     879         172 : static bool OGRCSVIsFalse(const char *pszStr)
     880             : {
     881         169 :     return EQUAL(pszStr, "f") || EQUAL(pszStr, "false") || EQUAL(pszStr, "n") ||
     882         341 :            EQUAL(pszStr, "no") || EQUAL(pszStr, "off");
     883             : }
     884             : 
     885             : /************************************************************************/
     886             : /*                        AutodetectFieldTypes()                        */
     887             : /************************************************************************/
     888             : 
     889          25 : char **OGRCSVLayer::AutodetectFieldTypes(CSLConstList papszOpenOptions,
     890             :                                          int nFieldCount)
     891             : {
     892             :     const bool bStreaming =
     893          50 :         STARTS_WITH(pszFilename, "/vsistdin") ||
     894             :         // config option for testing purposes only
     895          25 :         CPLTestBool(CPLGetConfigOption("OGR_CSV_SIMULATE_VSISTDIN", "NO"));
     896          25 :     constexpr int STREAMING_LIMIT = 1000 * 1000;
     897             :     // Use 1 000 000 as default maximum distance to be compatible with
     898             :     // /vsistdin/ caching.
     899          25 :     vsi_l_offset nBytes = static_cast<vsi_l_offset>(CPLAtoGIntBig(
     900             :         CSLFetchNameValueDef(papszOpenOptions, "AUTODETECT_SIZE_LIMIT",
     901          25 :                              CPLSPrintf("%d", STREAMING_LIMIT))));
     902          25 :     if (nBytes == 0)
     903           2 :         nBytes = static_cast<vsi_l_offset>(-1);  // unlimited size
     904          25 :     if (bStreaming && (nBytes == 0 || nBytes > STREAMING_LIMIT))
     905             :     {
     906           1 :         CPLError(CE_Warning, CPLE_AppDefined,
     907             :                  "Limiting AUTODETECT_SIZE_LIMIT to %d for /vsistdin/",
     908             :                  STREAMING_LIMIT);
     909           1 :         nBytes = STREAMING_LIMIT;
     910             :     }
     911             : 
     912          25 :     ResetReading();
     913             : 
     914             :     const char *pszAutodetectWidth =
     915          25 :         CSLFetchNameValueDef(papszOpenOptions, "AUTODETECT_WIDTH", "NO");
     916             : 
     917          25 :     const bool bAutodetectWidthForIntOrReal = EQUAL(pszAutodetectWidth, "YES");
     918          41 :     const bool bAutodetectWidth = bAutodetectWidthForIntOrReal ||
     919          16 :                                   EQUAL(pszAutodetectWidth, "STRING_ONLY");
     920             : 
     921          25 :     const bool bQuotedFieldAsString = CPLTestBool(CSLFetchNameValueDef(
     922             :         papszOpenOptions, "QUOTED_FIELDS_AS_STRING", "NO"));
     923             : 
     924             :     // This will be returned as the result.
     925          25 :     char **papszFieldTypes = nullptr;
     926             : 
     927          25 :     char *pszData = nullptr;
     928          25 :     VSILFILE *fp = fpCSV;
     929          50 :     std::string osTmpMemFile;
     930          25 :     size_t nRead = 0;
     931          25 :     int nRequested = 0;
     932          25 :     if (bStreaming)
     933             :     {
     934             :         // The above ResetReading() will skip the header line,
     935             :         // so VSIFTellL(fpCSV) != 0
     936           2 :         nRequested =
     937           2 :             static_cast<int>(nBytes) - static_cast<int>(VSIFTellL(fpCSV));
     938           2 :         if (nRequested <= 0)
     939           0 :             return nullptr;
     940           2 :         pszData = static_cast<char *>(VSI_MALLOC_VERBOSE(nRequested + 1));
     941           2 :         if (pszData == nullptr)
     942           0 :             return nullptr;
     943           2 :         nRead = VSIFReadL(pszData, 1, nRequested, fpCSV);
     944           2 :         pszData[nRead] = 0;
     945             : 
     946           2 :         osTmpMemFile = VSIMemGenerateHiddenFilename("temp.csv");
     947           2 :         fp = VSIFileFromMemBuffer(osTmpMemFile.c_str(),
     948             :                                   reinterpret_cast<GByte *>(pszData), nRead,
     949             :                                   FALSE);
     950             :     }
     951             : 
     952          50 :     std::vector<OGRFieldType> aeFieldType(nFieldCount);
     953          50 :     std::vector<int> abFieldBoolean(nFieldCount);
     954          50 :     std::vector<int> abFieldSet(nFieldCount);
     955          50 :     std::vector<int> abFinalTypeStringSet(nFieldCount);
     956          50 :     std::vector<int> anFieldWidth(nFieldCount);
     957          25 :     std::vector<int> anFieldPrecision(nFieldCount);
     958          25 :     int nStringFieldCount = 0;
     959             : 
     960          95 :     while (!fp->Eof() && !fp->Error())
     961             :     {
     962             :         char **papszTokens =
     963         170 :             CSVReadParseLine3L(fp, m_nMaxLineSize, szDelimiter,
     964             :                                true,  // bHonourStrings
     965          85 :                                bQuotedFieldAsString, bMergeDelimiter,
     966             :                                true  // bSkipBOM
     967             :             );
     968             :         // Can happen if we just reach EOF while trying to read new bytes.
     969          85 :         if (papszTokens == nullptr)
     970           0 :             break;
     971             : 
     972          85 :         if (bStreaming)
     973             :         {
     974             :             // Ignore last line if it is truncated.
     975          13 :             if (fp->Eof() && nRead == static_cast<size_t>(nRequested) &&
     976          13 :                 pszData[nRead - 1] != 13 && pszData[nRead - 1] != 10)
     977             :             {
     978           1 :                 CSLDestroy(papszTokens);
     979           1 :                 break;
     980             :             }
     981             :         }
     982          74 :         else if (VSIFTellL(fp) > nBytes)
     983             :         {
     984          13 :             CSLDestroy(papszTokens);
     985          13 :             break;
     986             :         }
     987             : 
     988        1192 :         for (int iField = 0;
     989        1192 :              iField < nFieldCount && papszTokens[iField] != nullptr; iField++)
     990             :         {
     991        1121 :             if (papszTokens[iField][0] == 0)
     992         482 :                 continue;
     993         695 :             if (abFinalTypeStringSet[iField] && !bAutodetectWidth)
     994          56 :                 continue;
     995         639 :             if (szDelimiter[0] == ';')
     996             :             {
     997           0 :                 char *chComma = strchr(papszTokens[iField], ',');
     998           0 :                 if (chComma)
     999           0 :                     *chComma = '.';
    1000             :             }
    1001         639 :             const CPLValueType eType = CPLGetValueType(papszTokens[iField]);
    1002             : 
    1003         639 :             if (bAutodetectWidth)
    1004             :             {
    1005         324 :                 int nFieldWidth = static_cast<int>(strlen(papszTokens[iField]));
    1006         324 :                 if (papszTokens[iField][0] == '"' &&
    1007           6 :                     papszTokens[iField][nFieldWidth - 1] == '"')
    1008             :                 {
    1009           6 :                     nFieldWidth -= 2;
    1010             :                 }
    1011         324 :                 int nFieldPrecision = 0;
    1012         324 :                 if (eType == CPL_VALUE_REAL && bAutodetectWidthForIntOrReal)
    1013             :                 {
    1014          40 :                     const char *pszDot = strchr(papszTokens[iField], '.');
    1015          40 :                     if (pszDot != nullptr)
    1016          40 :                         nFieldPrecision = static_cast<int>(strlen(pszDot + 1));
    1017             :                 }
    1018             : 
    1019         324 :                 if (nFieldWidth > anFieldWidth[iField])
    1020         205 :                     anFieldWidth[iField] = nFieldWidth;
    1021         324 :                 if (nFieldPrecision > anFieldPrecision[iField])
    1022          32 :                     anFieldPrecision[iField] = nFieldPrecision;
    1023             :             }
    1024             : 
    1025             :             OGRFieldType eOGRFieldType;
    1026         639 :             bool bIsBoolean = false;
    1027         639 :             if (eType == CPL_VALUE_INTEGER)
    1028             :             {
    1029         131 :                 GIntBig nVal = CPLAtoGIntBig(papszTokens[iField]);
    1030         131 :                 if (!CPL_INT64_FITS_ON_INT32(nVal))
    1031           6 :                     eOGRFieldType = OFTInteger64;
    1032             :                 else
    1033         125 :                     eOGRFieldType = OFTInteger;
    1034             :             }
    1035         508 :             else if (eType == CPL_VALUE_REAL ||
    1036         416 :                      EQUAL(papszTokens[iField], "inf") ||
    1037         415 :                      EQUAL(papszTokens[iField], "-inf") ||
    1038         414 :                      EQUAL(papszTokens[iField], "nan"))
    1039             :             {
    1040          95 :                 eOGRFieldType = OFTReal;
    1041             :             }
    1042         413 :             else if (abFieldSet[iField] && aeFieldType[iField] == OFTString)
    1043             :             {
    1044          38 :                 eOGRFieldType = OFTString;
    1045          38 :                 if (abFieldBoolean[iField])
    1046             :                 {
    1047          13 :                     abFieldBoolean[iField] =
    1048          21 :                         OGRCSVIsTrue(papszTokens[iField]) ||
    1049           8 :                         OGRCSVIsFalse(papszTokens[iField]);
    1050             :                 }
    1051             :             }
    1052             :             else
    1053             :             {
    1054             :                 OGRField sWrkField;
    1055         375 :                 CPLPushErrorHandler(CPLQuietErrorHandler);
    1056         375 :                 const bool bSuccess = CPL_TO_BOOL(
    1057         375 :                     OGRParseDate(papszTokens[iField], &sWrkField, 0));
    1058         375 :                 CPLPopErrorHandler();
    1059         375 :                 CPLErrorReset();
    1060         375 :                 if (bSuccess)
    1061             :                 {
    1062         209 :                     const bool bHasDate =
    1063         418 :                         strchr(papszTokens[iField], '/') != nullptr ||
    1064         209 :                         strchr(papszTokens[iField], '-') != nullptr;
    1065         209 :                     const bool bHasTime =
    1066         209 :                         strchr(papszTokens[iField], ':') != nullptr;
    1067         209 :                     if (bHasDate && bHasTime)
    1068          82 :                         eOGRFieldType = OFTDateTime;
    1069         127 :                     else if (bHasDate)
    1070          79 :                         eOGRFieldType = OFTDate;
    1071             :                     else
    1072          48 :                         eOGRFieldType = OFTTime;
    1073             :                 }
    1074             :                 else
    1075             :                 {
    1076         166 :                     eOGRFieldType = OFTString;
    1077         324 :                     bIsBoolean = OGRCSVIsTrue(papszTokens[iField]) ||
    1078         158 :                                  OGRCSVIsFalse(papszTokens[iField]);
    1079             :                 }
    1080             :             }
    1081             : 
    1082         166 :             const auto SetFinalStringType = [&abFinalTypeStringSet,
    1083             :                                              &aeFieldType, &nStringFieldCount,
    1084         664 :                                              iField]()
    1085             :             {
    1086         166 :                 if (!abFinalTypeStringSet[iField])
    1087             :                 {
    1088         166 :                     aeFieldType[iField] = OFTString;
    1089         166 :                     abFinalTypeStringSet[iField] = true;
    1090         166 :                     nStringFieldCount++;
    1091             :                 }
    1092         805 :             };
    1093             : 
    1094         639 :             if (!abFieldSet[iField])
    1095             :             {
    1096         356 :                 aeFieldType[iField] = eOGRFieldType;
    1097         356 :                 abFieldSet[iField] = TRUE;
    1098         356 :                 abFieldBoolean[iField] = bIsBoolean;
    1099         356 :                 if (eOGRFieldType == OFTString && !bIsBoolean)
    1100             :                 {
    1101          50 :                     SetFinalStringType();
    1102             :                 }
    1103             :             }
    1104         283 :             else if (aeFieldType[iField] != eOGRFieldType)
    1105             :             {
    1106             :                 // Promotion rules.
    1107         164 :                 if (aeFieldType[iField] == OFTInteger)
    1108             :                 {
    1109          39 :                     if (eOGRFieldType == OFTInteger64 ||
    1110             :                         eOGRFieldType == OFTReal)
    1111          16 :                         aeFieldType[iField] = eOGRFieldType;
    1112             :                     else
    1113             :                     {
    1114          23 :                         SetFinalStringType();
    1115             :                     }
    1116             :                 }
    1117         125 :                 else if (aeFieldType[iField] == OFTInteger64)
    1118             :                 {
    1119           2 :                     if (eOGRFieldType == OFTReal)
    1120           1 :                         aeFieldType[iField] = eOGRFieldType;
    1121           1 :                     else if (eOGRFieldType != OFTInteger)
    1122             :                     {
    1123           0 :                         SetFinalStringType();
    1124             :                     }
    1125             :                 }
    1126         123 :                 else if (aeFieldType[iField] == OFTReal)
    1127             :                 {
    1128          35 :                     if (eOGRFieldType != OFTInteger &&
    1129             :                         eOGRFieldType != OFTInteger64)
    1130             :                     {
    1131          20 :                         SetFinalStringType();
    1132             :                     }
    1133             :                 }
    1134          88 :                 else if (aeFieldType[iField] == OFTDate)
    1135             :                 {
    1136          31 :                     if (eOGRFieldType == OFTDateTime)
    1137          14 :                         aeFieldType[iField] = OFTDateTime;
    1138             :                     else
    1139             :                     {
    1140          17 :                         SetFinalStringType();
    1141             :                     }
    1142             :                 }
    1143          57 :                 else if (aeFieldType[iField] == OFTDateTime)
    1144             :                 {
    1145          40 :                     if (eOGRFieldType != OFTDate)
    1146             :                     {
    1147          26 :                         SetFinalStringType();
    1148             :                     }
    1149             :                 }
    1150          17 :                 else if (aeFieldType[iField] == OFTTime)
    1151             :                 {
    1152          17 :                     SetFinalStringType();
    1153             :                 }
    1154             :             }
    1155         213 :             else if (!abFinalTypeStringSet[iField] &&
    1156         213 :                      eOGRFieldType == OFTString && !bIsBoolean)
    1157             :             {
    1158          13 :                 SetFinalStringType();
    1159             :             }
    1160             :         }
    1161             : 
    1162          71 :         CSLDestroy(papszTokens);
    1163             : 
    1164             :         // If all fields are String and we don't need to compute width,
    1165             :         // just stop auto-detection now.
    1166          71 :         if (nStringFieldCount == nFieldCount && !bAutodetectWidth)
    1167             :         {
    1168           1 :             CPLDebugOnly("CSV",
    1169             :                          "AutodetectFieldTypes() stopped after "
    1170             :                          "reading " CPL_FRMT_GUIB " bytes",
    1171             :                          static_cast<GUIntBig>(VSIFTellL(fp)));
    1172           1 :             break;
    1173             :         }
    1174             :     }
    1175             : 
    1176             :     papszFieldTypes =
    1177          25 :         static_cast<char **>(CPLCalloc(nFieldCount + 1, sizeof(char *)));
    1178         402 :     for (int iField = 0; iField < nFieldCount; iField++)
    1179             :     {
    1180         377 :         CPLString osFieldType;
    1181         377 :         if (!abFieldSet[iField])
    1182          21 :             osFieldType = "String";
    1183         356 :         else if (aeFieldType[iField] == OFTInteger)
    1184          42 :             osFieldType = "Integer";
    1185         314 :         else if (aeFieldType[iField] == OFTInteger64)
    1186           3 :             osFieldType = "Integer64";
    1187         311 :         else if (aeFieldType[iField] == OFTReal)
    1188          52 :             osFieldType = "Real";
    1189         259 :         else if (aeFieldType[iField] == OFTDateTime)
    1190          56 :             osFieldType = "DateTime";
    1191         203 :         else if (aeFieldType[iField] == OFTDate)
    1192          20 :             osFieldType = "Date";
    1193         183 :         else if (aeFieldType[iField] == OFTTime)
    1194          17 :             osFieldType = "Time";
    1195         166 :         else if (aeFieldType[iField] == OFTStringList)
    1196           0 :             osFieldType = "JSonStringList";
    1197         166 :         else if (aeFieldType[iField] == OFTIntegerList)
    1198           0 :             osFieldType = "JSonIntegerList";
    1199         166 :         else if (aeFieldType[iField] == OFTInteger64List)
    1200           0 :             osFieldType = "JSonInteger64List";
    1201         166 :         else if (aeFieldType[iField] == OFTRealList)
    1202           0 :             osFieldType = "JSonRealList";
    1203         166 :         else if (abFieldBoolean[iField])
    1204          10 :             osFieldType = "Integer(Boolean)";
    1205             :         else
    1206         156 :             osFieldType = "String";
    1207             : 
    1208         377 :         if (!abFieldBoolean[iField])
    1209             :         {
    1210         541 :             if (anFieldWidth[iField] > 0 &&
    1211         174 :                 (aeFieldType[iField] == OFTString ||
    1212          95 :                  (bAutodetectWidthForIntOrReal &&
    1213          95 :                   (aeFieldType[iField] == OFTInteger ||
    1214          72 :                    aeFieldType[iField] == OFTInteger64))))
    1215             :             {
    1216          91 :                 osFieldType += CPLSPrintf(" (%d)", anFieldWidth[iField]);
    1217             :             }
    1218         348 :             else if (anFieldWidth[iField] > 0 && bAutodetectWidthForIntOrReal &&
    1219          72 :                      aeFieldType[iField] == OFTReal)
    1220             :             {
    1221          24 :                 osFieldType += CPLSPrintf(" (%d.%d)", anFieldWidth[iField],
    1222          24 :                                           anFieldPrecision[iField]);
    1223             :             }
    1224             :         }
    1225             : 
    1226         377 :         papszFieldTypes[iField] = CPLStrdup(osFieldType);
    1227             :     }
    1228             : 
    1229          25 :     if (bStreaming)
    1230             :     {
    1231           2 :         VSIFCloseL(fp);
    1232           2 :         VSIUnlink(osTmpMemFile.c_str());
    1233           2 :         VSIFree(pszData);
    1234             :     }
    1235             : 
    1236          25 :     ResetReading();
    1237             : 
    1238          25 :     return papszFieldTypes;
    1239             : }
    1240             : 
    1241             : /************************************************************************/
    1242             : /*                            ~OGRCSVLayer()                            */
    1243             : /************************************************************************/
    1244             : 
    1245        1552 : OGRCSVLayer::~OGRCSVLayer()
    1246             : 
    1247             : {
    1248         776 :     if (m_nFeaturesRead > 0)
    1249             :     {
    1250         954 :         CPLDebug("CSV", "%d features read on layer '%s'.",
    1251         477 :                  static_cast<int>(m_nFeaturesRead), poFeatureDefn->GetName());
    1252             :     }
    1253             : 
    1254             :     // Make sure the header file is written even if no features are written.
    1255         776 :     if (bNew && bInWriteMode)
    1256          27 :         WriteHeader();
    1257             : 
    1258         776 :     CPLFree(panGeomFieldIndex);
    1259             : 
    1260         776 :     poFeatureDefn->Release();
    1261         776 :     CPLFree(pszFilename);
    1262             : 
    1263         776 :     if (fpCSV)
    1264         776 :         VSIFCloseL(fpCSV);
    1265        1552 : }
    1266             : 
    1267             : /************************************************************************/
    1268             : /*                            ResetReading()                            */
    1269             : /************************************************************************/
    1270             : 
    1271        3766 : void OGRCSVLayer::ResetReading()
    1272             : 
    1273             : {
    1274        3766 :     if (fpCSV)
    1275        3766 :         VSIRewindL(fpCSV);
    1276             : 
    1277        3766 :     if (bHasFieldNames)
    1278        3638 :         CSLDestroy(CSVReadParseLine3L(fpCSV, m_nMaxLineSize, szDelimiter,
    1279        3638 :                                       bHonourStrings,
    1280             :                                       false,  // bKeepLeadingAndClosingQuotes
    1281             :                                       false,  // bMergeDelimiter,
    1282             :                                       true    // bSkipBOM
    1283             :                                       ));
    1284             : 
    1285        3766 :     bNeedRewindBeforeRead = false;
    1286             : 
    1287        3766 :     nNextFID = 1;
    1288        3766 : }
    1289             : 
    1290             : /************************************************************************/
    1291             : /*                        GetNextLineTokens()                           */
    1292             : /************************************************************************/
    1293             : 
    1294       48815 : char **OGRCSVLayer::GetNextLineTokens()
    1295             : {
    1296             :     while (true)
    1297             :     {
    1298             :         // Read the CSV record.
    1299       97630 :         char **papszTokens = CSVReadParseLine3L(
    1300       48815 :             fpCSV, m_nMaxLineSize, szDelimiter, bHonourStrings,
    1301             :             false,  // bKeepLeadingAndClosingQuotes
    1302       48815 :             bMergeDelimiter,
    1303             :             true  // bSkipBOM
    1304             :         );
    1305       48815 :         if (papszTokens == nullptr)
    1306        1387 :             return nullptr;
    1307             : 
    1308       47428 :         if (papszTokens[0] != nullptr)
    1309       47428 :             return papszTokens;
    1310             : 
    1311           0 :         CSLDestroy(papszTokens);
    1312           0 :     }
    1313             : }
    1314             : 
    1315             : /************************************************************************/
    1316             : /*                             GetFeature()                             */
    1317             : /************************************************************************/
    1318             : 
    1319          59 : OGRFeature *OGRCSVLayer::GetFeature(GIntBig nFID)
    1320             : {
    1321          59 :     if (nFID < 1 || fpCSV == nullptr)
    1322           7 :         return nullptr;
    1323          52 :     if (nFID < nNextFID || bNeedRewindBeforeRead)
    1324          20 :         ResetReading();
    1325         109 :     while (nNextFID < nFID)
    1326             :     {
    1327          71 :         char **papszTokens = GetNextLineTokens();
    1328          71 :         if (papszTokens == nullptr)
    1329          14 :             return nullptr;
    1330          57 :         CSLDestroy(papszTokens);
    1331          57 :         nNextFID++;
    1332             :     }
    1333          38 :     return GetNextUnfilteredFeature();
    1334             : }
    1335             : 
    1336             : /************************************************************************/
    1337             : /*                      GetNextUnfilteredFeature()                      */
    1338             : /************************************************************************/
    1339             : 
    1340       47933 : OGRFeature *OGRCSVLayer::GetNextUnfilteredFeature()
    1341             : 
    1342             : {
    1343       47933 :     if (fpCSV == nullptr)
    1344           0 :         return nullptr;
    1345             : 
    1346             :     // Read the CSV record.
    1347       47933 :     char **papszTokens = GetNextLineTokens();
    1348       47933 :     if (papszTokens == nullptr)
    1349        1347 :         return nullptr;
    1350             : 
    1351             :     // Create the OGR feature.
    1352       46586 :     OGRFeature *poFeature = new OGRFeature(poFeatureDefn);
    1353             : 
    1354             :     // Set attributes for any indicated attribute records.
    1355       46586 :     int iOGRField = 0;
    1356             :     const int nAttrCount = std::min(
    1357       46586 :         CSLCount(papszTokens), nCSVFieldCount + (bHiddenWKTColumn ? 1 : 0));
    1358             : 
    1359      257048 :     for (int iAttr = 0; !bIsEurostatTSV && iAttr < nAttrCount; iAttr++)
    1360             :     {
    1361             : 
    1362             :         // Skip deleted fields if OGR_SCHEMA with schemaType=Full was specified and fields were removed
    1363      210462 :         if (OGRCSVDataSource *poCsvDs = static_cast<OGRCSVDataSource *>(m_poDS))
    1364             :         {
    1365      210462 :             if (!poCsvDs->DeletedFieldIndexes().empty())
    1366             :             {
    1367             :                 const auto &deletedFieldIndexes =
    1368          14 :                     poCsvDs->DeletedFieldIndexes();
    1369          24 :                 if (std::find(deletedFieldIndexes.cbegin(),
    1370             :                               deletedFieldIndexes.cend(),
    1371          14 :                               iAttr) != deletedFieldIndexes.cend())
    1372             :                 {
    1373          40 :                     continue;
    1374             :                 }
    1375             :             }
    1376             :         }
    1377             : 
    1378      210452 :         if ((iAttr == iLongitudeField || iAttr == iLatitudeField ||
    1379      209574 :              iAttr == iZField) &&
    1380        1282 :             !bKeepGeomColumns)
    1381             :         {
    1382          14 :             continue;
    1383             :         }
    1384      210438 :         int iGeom = 0;
    1385      210438 :         if (bHiddenWKTColumn)
    1386             :         {
    1387          18 :             if (iAttr != 0)
    1388           9 :                 iGeom = panGeomFieldIndex[iAttr - 1];
    1389             :         }
    1390             :         else
    1391             :         {
    1392      210420 :             iGeom = panGeomFieldIndex[iAttr];
    1393             :         }
    1394      210438 :         if (iGeom >= 0)
    1395             :         {
    1396             :             const OGRGeomFieldDefn *poGeomFieldDefn =
    1397        3493 :                 poFeatureDefn->GetGeomFieldDefn(iGeom);
    1398        6218 :             if (papszTokens[iAttr][0] != '\0' &&
    1399        2725 :                 !(poGeomFieldDefn->IsIgnored()))
    1400             :             {
    1401        2154 :                 const char *pszStr = papszTokens[iAttr];
    1402        2154 :                 while (*pszStr == ' ')
    1403           0 :                     pszStr++;
    1404        4308 :                 std::unique_ptr<OGRGeometry> poGeom = nullptr;
    1405             :                 OGRErr eErr;
    1406             : 
    1407        2154 :                 if (EQUAL(poGeomFieldDefn->GetNameRef(), ""))
    1408             :                 {
    1409         315 :                     std::tie(poGeom, eErr) =
    1410         630 :                         OGRGeometryFactory::createFromWkt(pszStr);
    1411         315 :                     if (eErr != OGRERR_NONE)
    1412             :                     {
    1413           1 :                         CPLError(CE_Warning, CPLE_AppDefined,
    1414             :                                  "Ignoring invalid WKT: %s", pszStr);
    1415             :                     }
    1416             :                 }
    1417             :                 else
    1418             :                 {
    1419        3678 :                     CPLErrorHandlerPusher oErrorHandler(CPLQuietErrorHandler);
    1420             : 
    1421        1839 :                     std::tie(poGeom, eErr) =
    1422        3678 :                         OGRGeometryFactory::createFromWkt(pszStr);
    1423             : 
    1424        1839 :                     if (!poGeom && *pszStr == '{')
    1425             :                     {
    1426           1 :                         poGeom.reset(OGRGeometry::FromHandle(
    1427             :                             OGR_G_CreateGeometryFromJson(pszStr)));
    1428             :                     }
    1429        1839 :                     else if (!poGeom && ((*pszStr >= '0' && *pszStr <= '9') ||
    1430           1 :                                          (*pszStr >= 'a' && *pszStr <= 'z') ||
    1431           0 :                                          (*pszStr >= 'A' && *pszStr <= 'Z')))
    1432             :                     {
    1433           5 :                         poGeom.reset(
    1434             :                             OGRGeometryFromHexEWKB(pszStr, nullptr, FALSE));
    1435             :                     }
    1436             :                 }
    1437             : 
    1438        2154 :                 if (poGeom)
    1439             :                 {
    1440        4304 :                     poGeom->assignSpatialReference(
    1441        2152 :                         poGeomFieldDefn->GetSpatialRef());
    1442        2152 :                     poFeature->SetGeomField(iGeom, std::move(poGeom));
    1443             :                 }
    1444             :             }
    1445             : 
    1446        3493 :             const bool bHasAttributeField =
    1447        3493 :                 bKeepGeomColumns && !(iAttr == 0 && bHiddenWKTColumn);
    1448        3493 :             if (!bHasAttributeField)
    1449          16 :                 continue;
    1450             :         }
    1451             : 
    1452             :         const OGRFieldDefn *poFieldDefn =
    1453      210422 :             poFeatureDefn->GetFieldDefn(iOGRField);
    1454      210422 :         const OGRFieldType eFieldType = poFieldDefn->GetType();
    1455      210422 :         const OGRFieldSubType eFieldSubType = poFieldDefn->GetSubType();
    1456             : 
    1457          38 :         const auto WarnOnceBadValue = [this, poFieldDefn]()
    1458             :         {
    1459          22 :             if (!bWarningBadTypeOrWidth)
    1460             :             {
    1461           8 :                 bWarningBadTypeOrWidth = true;
    1462           8 :                 CPLError(CE_Warning, CPLE_AppDefined,
    1463             :                          "Invalid value type found in record %d for field %s. "
    1464             :                          "This warning will no longer be emitted",
    1465             :                          nNextFID, poFieldDefn->GetNameRef());
    1466             :             };
    1467      210444 :         };
    1468             : 
    1469          36 :         const auto WarnTooLargeWidth = [this, poFieldDefn]()
    1470             :         {
    1471          12 :             if (!bWarningBadTypeOrWidth)
    1472             :             {
    1473          12 :                 bWarningBadTypeOrWidth = true;
    1474          12 :                 CPLError(CE_Warning, CPLE_AppDefined,
    1475             :                          "Value with a width greater than field width "
    1476             :                          "found in record %d for field %s. "
    1477             :                          "This warning will no longer be emitted",
    1478             :                          nNextFID, poFieldDefn->GetNameRef());
    1479             :             };
    1480      210434 :         };
    1481             : 
    1482      210422 :         if (eFieldType == OFTInteger && eFieldSubType == OFSTBoolean)
    1483             :         {
    1484          14 :             if (papszTokens[iAttr][0] != '\0' && !poFieldDefn->IsIgnored())
    1485             :             {
    1486          21 :                 if (OGRCSVIsTrue(papszTokens[iAttr]) ||
    1487           7 :                     strcmp(papszTokens[iAttr], "1") == 0)
    1488             :                 {
    1489           8 :                     poFeature->SetField(iOGRField, 1);
    1490             :                 }
    1491           7 :                 else if (OGRCSVIsFalse(papszTokens[iAttr]) ||
    1492           1 :                          strcmp(papszTokens[iAttr], "0") == 0)
    1493             :                 {
    1494           5 :                     poFeature->SetField(iOGRField, 0);
    1495             :                 }
    1496             :                 else
    1497             :                 {
    1498             :                     // Set to TRUE because it's different than 0 but emit a warning
    1499           1 :                     poFeature->SetField(iOGRField, 1);
    1500           1 :                     WarnOnceBadValue();
    1501             :                 }
    1502             :             }
    1503             :         }
    1504      210408 :         else if (eFieldType == OFTInteger || eFieldType == OFTInteger64)
    1505             :         {
    1506         224 :             if (papszTokens[iAttr][0] != '\0' && !poFieldDefn->IsIgnored())
    1507             :             {
    1508         157 :                 char *endptr = nullptr;
    1509             :                 const GIntBig nVal = static_cast<GIntBig>(
    1510         157 :                     std::strtoll(papszTokens[iAttr], &endptr, 10));
    1511         157 :                 if (endptr == papszTokens[iAttr] + strlen(papszTokens[iAttr]))
    1512             :                 {
    1513         144 :                     poFeature->SetField(iOGRField, nVal);
    1514         139 :                     if (!bWarningBadTypeOrWidth &&
    1515         283 :                         poFieldDefn->GetWidth() > 0 &&
    1516          17 :                         static_cast<int>(strlen(papszTokens[iAttr])) >
    1517          17 :                             poFieldDefn->GetWidth())
    1518             :                     {
    1519           1 :                         WarnTooLargeWidth();
    1520             :                     }
    1521             :                 }
    1522             :                 else
    1523             :                 {
    1524          13 :                     WarnOnceBadValue();
    1525             :                 }
    1526         224 :             }
    1527             :         }
    1528      210184 :         else if (eFieldType == OFTReal)
    1529             :         {
    1530        3367 :             if (papszTokens[iAttr][0] != '\0' && !poFieldDefn->IsIgnored())
    1531             :             {
    1532        2900 :                 char *chComma = strchr(papszTokens[iAttr], ',');
    1533        2900 :                 if (chComma)
    1534           5 :                     *chComma = '.';
    1535        2900 :                 char *endptr = nullptr;
    1536             :                 const double dfVal =
    1537        2900 :                     CPLStrtodDelim(papszTokens[iAttr], &endptr, '.');
    1538        2900 :                 if (endptr == papszTokens[iAttr] + strlen(papszTokens[iAttr]))
    1539             :                 {
    1540        2893 :                     poFeature->SetField(iOGRField, dfVal);
    1541        2889 :                     if (!bWarningBadTypeOrWidth &&
    1542        5782 :                         poFieldDefn->GetWidth() > 0 &&
    1543          53 :                         static_cast<int>(strlen(papszTokens[iAttr])) >
    1544          53 :                             poFieldDefn->GetWidth())
    1545             :                     {
    1546          10 :                         WarnTooLargeWidth();
    1547             :                     }
    1548        5762 :                     else if (!bWarningBadTypeOrWidth &&
    1549        2879 :                              poFieldDefn->GetWidth() > 0)
    1550             :                     {
    1551          43 :                         const char *pszDot = strchr(papszTokens[iAttr], '.');
    1552          43 :                         const int nPrecision =
    1553             :                             pszDot != nullptr
    1554          43 :                                 ? static_cast<int>(strlen(pszDot + 1))
    1555             :                                 : 0;
    1556          43 :                         if (nPrecision > poFieldDefn->GetPrecision())
    1557             :                         {
    1558           1 :                             bWarningBadTypeOrWidth = true;
    1559           1 :                             CPLError(CE_Warning, CPLE_AppDefined,
    1560             :                                      "Value with a precision greater than "
    1561             :                                      "field precision found in record %d for "
    1562             :                                      "field %s. "
    1563             :                                      "This warning will no longer be emitted",
    1564             :                                      nNextFID, poFieldDefn->GetNameRef());
    1565             :                         }
    1566             :                     }
    1567             :                 }
    1568             :                 else
    1569             :                 {
    1570           7 :                     WarnOnceBadValue();
    1571             :                 }
    1572             :             }
    1573             :         }
    1574      206817 :         else if (eFieldType != OFTString)
    1575             :         {
    1576         218 :             if (papszTokens[iAttr][0] != '\0' && !poFieldDefn->IsIgnored())
    1577             :             {
    1578         109 :                 poFeature->SetField(iOGRField, papszTokens[iAttr]);
    1579         212 :                 if (!bWarningBadTypeOrWidth &&
    1580         103 :                     !poFeature->IsFieldSetAndNotNull(iOGRField))
    1581             :                 {
    1582           1 :                     WarnOnceBadValue();
    1583             :                 }
    1584             :             }
    1585             :         }
    1586      206599 :         else if (!poFieldDefn->IsIgnored())
    1587             :         {
    1588      204941 :             if (bEmptyStringNull && papszTokens[iAttr][0] == '\0')
    1589             :             {
    1590           1 :                 poFeature->SetFieldNull(iOGRField);
    1591             :             }
    1592             :             else
    1593             :             {
    1594      204940 :                 poFeature->SetField(iOGRField, papszTokens[iAttr]);
    1595      204985 :                 if (!bWarningBadTypeOrWidth && poFieldDefn->GetWidth() > 0 &&
    1596          45 :                     static_cast<int>(strlen(papszTokens[iAttr])) >
    1597          45 :                         poFieldDefn->GetWidth())
    1598             :                 {
    1599           1 :                     WarnTooLargeWidth();
    1600             :                 }
    1601             :             }
    1602             :         }
    1603             : 
    1604      210422 :         if (bKeepSourceColumns && eFieldType != OFTString)
    1605             :         {
    1606          11 :             iOGRField++;
    1607          21 :             if (papszTokens[iAttr][0] != '\0' &&
    1608          10 :                 !poFeatureDefn->GetFieldDefn(iOGRField)->IsIgnored())
    1609             :             {
    1610          10 :                 poFeature->SetField(iOGRField, papszTokens[iAttr]);
    1611             :             }
    1612             :         }
    1613             : 
    1614      210422 :         iOGRField++;
    1615             :     }
    1616             : 
    1617             :     // Eurostat TSV files.
    1618             : 
    1619       46590 :     for (int iAttr = 0; bIsEurostatTSV && iAttr < nAttrCount; iAttr++)
    1620             :     {
    1621           4 :         if (iAttr == 0)
    1622             :         {
    1623           1 :             char **papszDims = CSLTokenizeString2(papszTokens[0], ",", 0);
    1624           1 :             if (CSLCount(papszDims) != nEurostatDims)
    1625             :             {
    1626           0 :                 CSLDestroy(papszDims);
    1627           0 :                 break;
    1628             :             }
    1629           3 :             for (int iSubAttr = 0; iSubAttr < nEurostatDims; iSubAttr++)
    1630             :             {
    1631           2 :                 if (!poFeatureDefn->GetFieldDefn(iSubAttr)->IsIgnored())
    1632           2 :                     poFeature->SetField(iSubAttr, papszDims[iSubAttr]);
    1633             :             }
    1634           1 :             CSLDestroy(papszDims);
    1635             :         }
    1636             :         else
    1637             :         {
    1638           3 :             char **papszVals = CSLTokenizeString2(papszTokens[iAttr], " ", 0);
    1639           3 :             CPLValueType eType = CPLGetValueType(papszVals[0]);
    1640           3 :             if ((papszVals[0] && papszVals[0][0] != '\0') &&
    1641           2 :                 (eType == CPL_VALUE_INTEGER || eType == CPL_VALUE_REAL))
    1642             :             {
    1643           2 :                 if (!poFeatureDefn
    1644           2 :                          ->GetFieldDefn(nEurostatDims + 2 * (iAttr - 1))
    1645           2 :                          ->IsIgnored())
    1646           2 :                     poFeature->SetField(nEurostatDims + 2 * (iAttr - 1),
    1647             :                                         papszVals[0]);
    1648             :             }
    1649           3 :             if (CSLCount(papszVals) == 2)
    1650             :             {
    1651           1 :                 if (!poFeatureDefn
    1652           1 :                          ->GetFieldDefn(nEurostatDims + 2 * (iAttr - 1) + 1)
    1653           1 :                          ->IsIgnored())
    1654           1 :                     poFeature->SetField(nEurostatDims + 2 * (iAttr - 1) + 1,
    1655           1 :                                         papszVals[1]);
    1656             :             }
    1657           3 :             CSLDestroy(papszVals);
    1658             :         }
    1659             :     }
    1660             : 
    1661             :     // Is it a numeric value parsable by local-aware CPLAtofM()
    1662        1271 :     const auto IsCPLAtofMParsable = [](char *pszVal)
    1663             :     {
    1664        1271 :         auto l_eType = CPLGetValueType(pszVal);
    1665        1271 :         if (l_eType == CPL_VALUE_INTEGER || l_eType == CPL_VALUE_REAL)
    1666        1271 :             return true;
    1667           0 :         char *pszComma = strchr(pszVal, ',');
    1668           0 :         if (pszComma)
    1669             :         {
    1670           0 :             *pszComma = '.';
    1671           0 :             l_eType = CPLGetValueType(pszVal);
    1672           0 :             *pszComma = ',';
    1673             :         }
    1674           0 :         return l_eType == CPL_VALUE_REAL;
    1675             :     };
    1676             : 
    1677             :     // http://www.faa.gov/airports/airport_safety/airportdata_5010/menu/index.cfm
    1678             :     // specific
    1679             : 
    1680       46586 :     if (iNfdcLatitudeS != -1 && iNfdcLongitudeS != -1 &&
    1681           0 :         nAttrCount > iNfdcLatitudeS && nAttrCount > iNfdcLongitudeS &&
    1682           0 :         papszTokens[iNfdcLongitudeS][0] != 0 &&
    1683           0 :         papszTokens[iNfdcLatitudeS][0] != 0)
    1684             :     {
    1685             :         const double dfLon =
    1686           0 :             CPLAtof(papszTokens[iNfdcLongitudeS]) / 3600.0 *
    1687           0 :             (strchr(papszTokens[iNfdcLongitudeS], 'W') ? -1.0 : 1.0);
    1688             :         const double dfLat =
    1689           0 :             CPLAtof(papszTokens[iNfdcLatitudeS]) / 3600.0 *
    1690           0 :             (strchr(papszTokens[iNfdcLatitudeS], 'S') ? -1.0 : 1.0);
    1691           0 :         if (!poFeatureDefn->GetGeomFieldDefn(0)->IsIgnored())
    1692           0 :             poFeature->SetGeometryDirectly(new OGRPoint(dfLon, dfLat));
    1693             :     }
    1694             : 
    1695         439 :     else if (iLatitudeField != -1 && iLongitudeField != -1 &&
    1696         439 :              nAttrCount > iLatitudeField && nAttrCount > iLongitudeField &&
    1697         439 :              papszTokens[iLongitudeField][0] != 0 &&
    1698         434 :              papszTokens[iLatitudeField][0] != 0 &&
    1699       47459 :              IsCPLAtofMParsable(papszTokens[iLongitudeField]) &&
    1700         434 :              IsCPLAtofMParsable(papszTokens[iLatitudeField]))
    1701             :     {
    1702         434 :         if (!m_bIsGNIS ||
    1703             :             // GNIS specific: some records have dummy 0,0 value.
    1704           0 :             (papszTokens[iLongitudeField][0] != DIGIT_ZERO ||
    1705           0 :              papszTokens[iLongitudeField][1] != '\0' ||
    1706           0 :              papszTokens[iLatitudeField][0] != DIGIT_ZERO ||
    1707           0 :              papszTokens[iLatitudeField][1] != '\0'))
    1708             :         {
    1709         434 :             const double dfLon = CPLAtofM(papszTokens[iLongitudeField]);
    1710         434 :             const double dfLat = CPLAtofM(papszTokens[iLatitudeField]);
    1711         434 :             if (!poFeatureDefn->GetGeomFieldDefn(0)->IsIgnored())
    1712             :             {
    1713         404 :                 if (iZField != -1 && nAttrCount > iZField &&
    1714        1241 :                     papszTokens[iZField][0] != 0 &&
    1715         403 :                     IsCPLAtofMParsable(papszTokens[iZField]))
    1716         403 :                     poFeature->SetGeometryDirectly(new OGRPoint(
    1717         403 :                         dfLon, dfLat, CPLAtofM(papszTokens[iZField])));
    1718             :                 else
    1719          31 :                     poFeature->SetGeometryDirectly(new OGRPoint(dfLon, dfLat));
    1720             :             }
    1721             :         }
    1722             :     }
    1723             : 
    1724       46586 :     CSLDestroy(papszTokens);
    1725             : 
    1726             :     // Translate the record id.
    1727       46586 :     poFeature->SetFID(nNextFID++);
    1728             : 
    1729       46586 :     m_nFeaturesRead++;
    1730             : 
    1731       46586 :     return poFeature;
    1732             : }
    1733             : 
    1734             : /************************************************************************/
    1735             : /*                           GetNextFeature()                           */
    1736             : /************************************************************************/
    1737             : 
    1738       47214 : OGRFeature *OGRCSVLayer::GetNextFeature()
    1739             : 
    1740             : {
    1741       47214 :     if (bNeedRewindBeforeRead)
    1742           3 :         ResetReading();
    1743             : 
    1744             :     // Read features till we find one that satisfies our current
    1745             :     // spatial criteria.
    1746             :     while (true)
    1747             :     {
    1748       47895 :         OGRFeature *poFeature = GetNextUnfilteredFeature();
    1749       47895 :         if (poFeature == nullptr)
    1750        1345 :             return nullptr;
    1751             : 
    1752       93444 :         if ((m_poFilterGeom == nullptr ||
    1753       92993 :              FilterGeometry(poFeature->GetGeomFieldRef(m_iGeomFieldFilter))) &&
    1754       46443 :             (m_poAttrQuery == nullptr || m_poAttrQuery->Evaluate(poFeature)))
    1755       45869 :             return poFeature;
    1756             : 
    1757         681 :         delete poFeature;
    1758         681 :     }
    1759             : }
    1760             : 
    1761             : /************************************************************************/
    1762             : /*                           TestCapability()                           */
    1763             : /************************************************************************/
    1764             : 
    1765        4208 : int OGRCSVLayer::TestCapability(const char *pszCap)
    1766             : 
    1767             : {
    1768        4208 :     if (EQUAL(pszCap, OLCSequentialWrite))
    1769         293 :         return bInWriteMode && !bKeepSourceColumns && bKeepGeomColumns;
    1770        3915 :     else if (EQUAL(pszCap, OLCCreateField))
    1771         871 :         return bNew && !bHasFieldNames;
    1772        3044 :     else if (EQUAL(pszCap, OLCCreateGeomField))
    1773          72 :         return bNew && !bHasFieldNames &&
    1774          72 :                eGeometryFormat == OGR_CSV_GEOM_AS_WKT;
    1775        3008 :     else if (EQUAL(pszCap, OLCIgnoreFields))
    1776        1815 :         return TRUE;
    1777        1193 :     else if (EQUAL(pszCap, OLCCurveGeometries))
    1778         146 :         return TRUE;
    1779        1047 :     else if (EQUAL(pszCap, OLCMeasuredGeometries))
    1780         277 :         return TRUE;
    1781         770 :     else if (EQUAL(pszCap, OLCZGeometries))
    1782          18 :         return TRUE;
    1783             :     else
    1784         752 :         return FALSE;
    1785             : }
    1786             : 
    1787             : /************************************************************************/
    1788             : /*                          PreCreateField()                            */
    1789             : /************************************************************************/
    1790             : 
    1791             : OGRCSVCreateFieldAction
    1792         818 : OGRCSVLayer::PreCreateField(OGRFeatureDefn *poFeatureDefn,
    1793             :                             const std::set<CPLString> &oSetFields,
    1794             :                             const OGRFieldDefn *poNewField, int bApproxOK)
    1795             : {
    1796             :     // Does this duplicate an existing field?
    1797         818 :     if (oSetFields.find(CPLString(poNewField->GetNameRef()).toupper()) !=
    1798        1636 :         oSetFields.end())
    1799             :     {
    1800           6 :         if (poFeatureDefn->GetGeomFieldIndex(poNewField->GetNameRef()) >= 0 ||
    1801           3 :             poFeatureDefn->GetGeomFieldIndex(
    1802           3 :                 CPLSPrintf("geom_%s", poNewField->GetNameRef())) >= 0)
    1803             :         {
    1804           2 :             return CREATE_FIELD_DO_NOTHING;
    1805             :         }
    1806           1 :         CPLError(CE_Failure, CPLE_AppDefined,
    1807             :                  "Attempt to create field %s, "
    1808             :                  "but a field with this name already exists.",
    1809             :                  poNewField->GetNameRef());
    1810             : 
    1811           1 :         return CREATE_FIELD_ERROR;
    1812             :     }
    1813             : 
    1814             :     // Is this a legal field type for CSV?
    1815         815 :     switch (poNewField->GetType())
    1816             :     {
    1817         815 :         case OFTInteger:
    1818             :         case OFTInteger64:
    1819             :         case OFTReal:
    1820             :         case OFTString:
    1821             :         case OFTIntegerList:
    1822             :         case OFTInteger64List:
    1823             :         case OFTRealList:
    1824             :         case OFTStringList:
    1825             :         case OFTTime:
    1826             :         case OFTDate:
    1827             :         case OFTDateTime:
    1828             :             // These types are OK.
    1829         815 :             break;
    1830             : 
    1831           0 :         default:
    1832           0 :             if (bApproxOK)
    1833             :             {
    1834           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
    1835             :                          "Attempt to create field of type %s, but this is not "
    1836             :                          "supported "
    1837             :                          "for .csv files.  Just treating as a plain string.",
    1838             :                          poNewField->GetFieldTypeName(poNewField->GetType()));
    1839             :             }
    1840             :             else
    1841             :             {
    1842           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
    1843             :                          "Attempt to create field of type %s, but this is not "
    1844             :                          "supported "
    1845             :                          "for .csv files.",
    1846             :                          poNewField->GetFieldTypeName(poNewField->GetType()));
    1847           0 :                 return CREATE_FIELD_ERROR;
    1848             :             }
    1849             :     }
    1850         815 :     return CREATE_FIELD_PROCEED;
    1851             : }
    1852             : 
    1853             : /************************************************************************/
    1854             : /*                            CreateField()                             */
    1855             : /************************************************************************/
    1856             : 
    1857         420 : OGRErr OGRCSVLayer::CreateField(const OGRFieldDefn *poNewField, int bApproxOK)
    1858             : 
    1859             : {
    1860             :     // If we have already written our field names, then we are not
    1861             :     // allowed to add new fields.
    1862         420 :     if (!TestCapability(OLCCreateField))
    1863             :     {
    1864           1 :         CPLError(CE_Failure, CPLE_AppDefined,
    1865             :                  "Unable to create new fields after first feature written.");
    1866           1 :         return OGRERR_FAILURE;
    1867             :     }
    1868             : 
    1869         419 :     if (nCSVFieldCount >= 10000)
    1870             :     {
    1871           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Limiting to 10000 fields");
    1872           0 :         return OGRERR_FAILURE;
    1873             :     }
    1874             : 
    1875         419 :     if (m_oSetFields.empty())
    1876             :     {
    1877         119 :         for (int i = 0; i < poFeatureDefn->GetFieldCount(); i++)
    1878             :         {
    1879             :             m_oSetFields.insert(
    1880          28 :                 CPLString(poFeatureDefn->GetFieldDefn(i)->GetNameRef())
    1881          28 :                     .toupper());
    1882             :         }
    1883             :     }
    1884             : 
    1885             :     const OGRCSVCreateFieldAction eAction =
    1886         419 :         PreCreateField(poFeatureDefn, m_oSetFields, poNewField, bApproxOK);
    1887         419 :     if (eAction == CREATE_FIELD_DO_NOTHING)
    1888           2 :         return OGRERR_NONE;
    1889         417 :     if (eAction == CREATE_FIELD_ERROR)
    1890           0 :         return OGRERR_FAILURE;
    1891             : 
    1892             :     // Seems ok, add to field list.
    1893         417 :     poFeatureDefn->AddFieldDefn(poNewField);
    1894         417 :     nCSVFieldCount++;
    1895         417 :     m_oSetFields.insert(CPLString(poNewField->GetNameRef()).toupper());
    1896             : 
    1897         834 :     panGeomFieldIndex = static_cast<int *>(CPLRealloc(
    1898         417 :         panGeomFieldIndex, sizeof(int) * poFeatureDefn->GetFieldCount()));
    1899         417 :     panGeomFieldIndex[poFeatureDefn->GetFieldCount() - 1] = -1;
    1900             : 
    1901         417 :     return OGRERR_NONE;
    1902             : }
    1903             : 
    1904             : /************************************************************************/
    1905             : /*                          CreateGeomField()                           */
    1906             : /************************************************************************/
    1907             : 
    1908          21 : OGRErr OGRCSVLayer::CreateGeomField(const OGRGeomFieldDefn *poGeomField,
    1909             :                                     int /* bApproxOK */)
    1910             : {
    1911          21 :     if (!TestCapability(OLCCreateGeomField))
    1912             :     {
    1913           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    1914             :                  "Unable to create new fields after first feature written.");
    1915           0 :         return OGRERR_FAILURE;
    1916             :     }
    1917             : 
    1918             :     // Does this duplicate an existing field?
    1919          21 :     if (poFeatureDefn->GetGeomFieldIndex(poGeomField->GetNameRef()) >= 0)
    1920             :     {
    1921           1 :         CPLError(CE_Failure, CPLE_AppDefined,
    1922             :                  "Attempt to create geom field %s, "
    1923             :                  "but a field with this name already exists.",
    1924             :                  poGeomField->GetNameRef());
    1925             : 
    1926           1 :         return OGRERR_FAILURE;
    1927             :     }
    1928          40 :     OGRGeomFieldDefn oGeomField(poGeomField);
    1929          20 :     auto poSRSOri = poGeomField->GetSpatialRef();
    1930          20 :     if (poSRSOri)
    1931             :     {
    1932           6 :         auto poSRS = poSRSOri->Clone();
    1933           6 :         poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
    1934           6 :         oGeomField.SetSpatialRef(poSRS);
    1935           6 :         poSRS->Release();
    1936             :     }
    1937          20 :     poFeatureDefn->AddGeomFieldDefn(&oGeomField);
    1938             : 
    1939          20 :     const char *pszName = poGeomField->GetNameRef();
    1940          20 :     if (EQUAL(pszName, ""))
    1941             :     {
    1942           3 :         const int nIdx = poFeatureDefn->GetFieldIndex("WKT");
    1943           3 :         if (nIdx >= 0)
    1944             :         {
    1945           0 :             panGeomFieldIndex[nIdx] = poFeatureDefn->GetGeomFieldCount() - 1;
    1946           0 :             return OGRERR_NONE;
    1947             :         }
    1948           3 :         pszName = "WKT";
    1949             :     }
    1950          20 :     if (STARTS_WITH_CI(pszName, "geom_") && strlen(pszName) >= strlen("geom_"))
    1951          15 :         pszName += strlen("geom_");
    1952          20 :     if (!EQUAL(pszName, "WKT") && !STARTS_WITH_CI(pszName, "_WKT"))
    1953           2 :         pszName = CPLSPrintf("_WKT%s", pszName);
    1954             : 
    1955          20 :     OGRFieldDefn oRegularFieldDefn(pszName, OFTString);
    1956          20 :     poFeatureDefn->AddFieldDefn(&oRegularFieldDefn);
    1957          20 :     nCSVFieldCount++;
    1958             : 
    1959          40 :     panGeomFieldIndex = static_cast<int *>(CPLRealloc(
    1960          20 :         panGeomFieldIndex, sizeof(int) * poFeatureDefn->GetFieldCount()));
    1961          40 :     panGeomFieldIndex[poFeatureDefn->GetFieldCount() - 1] =
    1962          20 :         poFeatureDefn->GetGeomFieldCount() - 1;
    1963             : 
    1964          20 :     return OGRERR_NONE;
    1965             : }
    1966             : 
    1967             : /************************************************************************/
    1968             : /*                            WriteHeader()                             */
    1969             : /*                                                                      */
    1970             : /*      Write the header, and possibly the .csvt file if they           */
    1971             : /*      haven't already been written.                                   */
    1972             : /************************************************************************/
    1973             : 
    1974         132 : OGRErr OGRCSVLayer::WriteHeader()
    1975             : {
    1976         132 :     if (!bNew)
    1977           0 :         return OGRERR_NONE;
    1978             : 
    1979             :     // Write field names if we haven't written them yet.
    1980             :     // Write .csvt file if needed.
    1981         132 :     bNew = false;
    1982         132 :     bHasFieldNames = true;
    1983         132 :     bool bOK = true;
    1984             : 
    1985         296 :     for (int iFile = 0; iFile < (bCreateCSVT ? 2 : 1); iFile++)
    1986             :     {
    1987         164 :         VSILFILE *fpCSVT = nullptr;
    1988         164 :         if (bCreateCSVT && iFile == 0)
    1989             :         {
    1990             :             char *pszDirName =
    1991          32 :                 CPLStrdup(CPLGetDirnameSafe(pszFilename).c_str());
    1992             :             char *pszBaseName =
    1993          32 :                 CPLStrdup(CPLGetBasenameSafe(pszFilename).c_str());
    1994          32 :             fpCSVT = VSIFOpenL(
    1995          64 :                 CPLFormFilenameSafe(pszDirName, pszBaseName, ".csvt").c_str(),
    1996             :                 "wb");
    1997          32 :             CPLFree(pszDirName);
    1998          32 :             CPLFree(pszBaseName);
    1999             :         }
    2000             :         else
    2001             :         {
    2002         132 :             if (STARTS_WITH(pszFilename, "/vsistdout/") ||
    2003         131 :                 STARTS_WITH(pszFilename, "/vsizip/"))
    2004           1 :                 fpCSV = VSIFOpenL(pszFilename, "wb");
    2005             :             else
    2006         131 :                 fpCSV = VSIFOpenL(pszFilename, "w+b");
    2007             : 
    2008         132 :             if (fpCSV == nullptr)
    2009             :             {
    2010           0 :                 CPLError(CE_Failure, CPLE_OpenFailed,
    2011             :                          "Failed to create %s:\n%s", pszFilename,
    2012           0 :                          VSIStrerror(errno));
    2013           0 :                 return OGRERR_FAILURE;
    2014             :             }
    2015             :         }
    2016             : 
    2017         164 :         if (bWriteBOM && fpCSV)
    2018             :         {
    2019           2 :             bOK &= VSIFWriteL("\xEF\xBB\xBF", 1, 3, fpCSV) > 0;
    2020             :         }
    2021             : 
    2022         164 :         bool bNeedDelimiter = false;
    2023         164 :         if (eGeometryFormat == OGR_CSV_GEOM_AS_XYZ)
    2024             :         {
    2025           3 :             if (fpCSV)
    2026           2 :                 bOK &=
    2027           2 :                     VSIFPrintfL(fpCSV, "X%sY%sZ", szDelimiter, szDelimiter) > 0;
    2028           3 :             if (fpCSVT)
    2029           1 :                 bOK &= VSIFPrintfL(fpCSVT, "%s", "CoordX,CoordY,Real") > 0;
    2030           3 :             bNeedDelimiter = true;
    2031             :         }
    2032         161 :         else if (eGeometryFormat == OGR_CSV_GEOM_AS_XY)
    2033             :         {
    2034           4 :             if (fpCSV)
    2035           2 :                 bOK &= VSIFPrintfL(fpCSV, "X%sY", szDelimiter) > 0;
    2036           4 :             if (fpCSVT)
    2037           2 :                 bOK &= VSIFPrintfL(fpCSVT, "%s", "CoordX,CoordY") > 0;
    2038           4 :             bNeedDelimiter = true;
    2039             :         }
    2040         157 :         else if (eGeometryFormat == OGR_CSV_GEOM_AS_YX)
    2041             :         {
    2042           2 :             if (fpCSV)
    2043           1 :                 bOK &= VSIFPrintfL(fpCSV, "Y%sX", szDelimiter) > 0;
    2044           2 :             if (fpCSVT)
    2045           1 :                 bOK &= VSIFPrintfL(fpCSVT, "%s", "CoordY,CoordX") > 0;
    2046           2 :             bNeedDelimiter = true;
    2047             :         }
    2048         155 :         else if (bHiddenWKTColumn)
    2049             :         {
    2050          49 :             if (fpCSV)
    2051             :             {
    2052             :                 const char *pszColName =
    2053          35 :                     poFeatureDefn->GetGeomFieldDefn(0)->GetNameRef();
    2054          35 :                 bOK &= VSIFPrintfL(fpCSV, "%s", pszColName) >= 0;
    2055             :             }
    2056          49 :             if (fpCSVT)
    2057          14 :                 bOK &= VSIFPrintfL(fpCSVT, "%s", "WKT") > 0;
    2058          49 :             bNeedDelimiter = true;
    2059             :         }
    2060             : 
    2061         778 :         for (int iField = 0; iField < poFeatureDefn->GetFieldCount(); iField++)
    2062             :         {
    2063         614 :             if (bNeedDelimiter)
    2064             :             {
    2065         526 :                 if (fpCSV)
    2066         363 :                     bOK &= VSIFPrintfL(fpCSV, "%s", szDelimiter) > 0;
    2067         526 :                 if (fpCSVT)
    2068         163 :                     bOK &= VSIFPrintfL(fpCSVT, "%s", ",") > 0;
    2069             :             }
    2070         614 :             bNeedDelimiter = true;
    2071             : 
    2072        1228 :             char *pszEscaped = CPLEscapeString(
    2073         614 :                 poFeatureDefn->GetFieldDefn(iField)->GetNameRef(), -1,
    2074         614 :                 m_eStringQuoting == StringQuoting::ALWAYS
    2075             :                     ? CPLES_CSV_FORCE_QUOTING
    2076             :                     : CPLES_CSV);
    2077         614 :             if (pszEscaped == nullptr)
    2078           0 :                 return OGRERR_FAILURE;
    2079             : 
    2080         614 :             if (fpCSV)
    2081             :             {
    2082         437 :                 bool bAddDoubleQuote = false;
    2083         437 :                 if (szDelimiter[0] == ' ' && pszEscaped[0] != '"' &&
    2084           2 :                     strchr(pszEscaped, ' ') != nullptr)
    2085           1 :                     bAddDoubleQuote = true;
    2086         437 :                 if (bAddDoubleQuote)
    2087           1 :                     bOK &= VSIFWriteL("\"", 1, 1, fpCSV) > 0;
    2088         437 :                 bOK &= VSIFPrintfL(fpCSV, "%s", pszEscaped) >= 0;
    2089         437 :                 if (bAddDoubleQuote)
    2090           1 :                     bOK &= VSIFWriteL("\"", 1, 1, fpCSV) > 0;
    2091             :             }
    2092         614 :             CPLFree(pszEscaped);
    2093             : 
    2094         614 :             if (fpCSVT)
    2095             :             {
    2096         177 :                 int nWidth = poFeatureDefn->GetFieldDefn(iField)->GetWidth();
    2097             :                 const int nPrecision =
    2098         177 :                     poFeatureDefn->GetFieldDefn(iField)->GetPrecision();
    2099             : 
    2100         177 :                 switch (poFeatureDefn->GetFieldDefn(iField)->GetType())
    2101             :                 {
    2102          54 :                     case OFTInteger:
    2103             :                     {
    2104          54 :                         if (poFeatureDefn->GetFieldDefn(iField)->GetSubType() ==
    2105             :                             OFSTBoolean)
    2106             :                         {
    2107           9 :                             nWidth = 0;
    2108           9 :                             bOK &= VSIFPrintfL(fpCSVT, "%s",
    2109           9 :                                                "Integer(Boolean)") > 0;
    2110             :                         }
    2111          90 :                         else if (poFeatureDefn->GetFieldDefn(iField)
    2112          45 :                                      ->GetSubType() == OFSTInt16)
    2113             :                         {
    2114          11 :                             nWidth = 0;
    2115          11 :                             bOK &=
    2116          11 :                                 VSIFPrintfL(fpCSVT, "%s", "Integer(Int16)") > 0;
    2117             :                         }
    2118             :                         else
    2119             :                         {
    2120          34 :                             bOK &= VSIFPrintfL(fpCSVT, "%s", "Integer") > 0;
    2121             :                         }
    2122          54 :                         break;
    2123             :                     }
    2124          14 :                     case OFTInteger64:
    2125          14 :                         bOK &= VSIFPrintfL(fpCSVT, "%s", "Integer64") > 0;
    2126          14 :                         break;
    2127          46 :                     case OFTReal:
    2128             :                     {
    2129          46 :                         if (poFeatureDefn->GetFieldDefn(iField)->GetSubType() ==
    2130             :                             OFSTFloat32)
    2131             :                         {
    2132          11 :                             nWidth = 0;
    2133          11 :                             bOK &=
    2134          11 :                                 VSIFPrintfL(fpCSVT, "%s", "Real(Float32)") > 0;
    2135             :                         }
    2136             :                         else
    2137             :                         {
    2138          35 :                             bOK &= VSIFPrintfL(fpCSVT, "%s", "Real") > 0;
    2139             :                         }
    2140          46 :                         break;
    2141             :                     }
    2142           6 :                     case OFTDate:
    2143           6 :                         bOK &= VSIFPrintfL(fpCSVT, "%s", "Date") > 0;
    2144           6 :                         break;
    2145           1 :                     case OFTTime:
    2146           1 :                         bOK &= VSIFPrintfL(fpCSVT, "%s", "Time") > 0;
    2147           1 :                         break;
    2148          11 :                     case OFTDateTime:
    2149          11 :                         bOK &= VSIFPrintfL(fpCSVT, "%s", "DateTime") > 0;
    2150          11 :                         break;
    2151           3 :                     case OFTStringList:
    2152           3 :                         bOK &= VSIFPrintfL(fpCSVT, "%s", "JSonStringList") > 0;
    2153           3 :                         break;
    2154           2 :                     case OFTIntegerList:
    2155           2 :                         bOK &= VSIFPrintfL(fpCSVT, "%s", "JSonIntegerList") > 0;
    2156           2 :                         break;
    2157           2 :                     case OFTInteger64List:
    2158           2 :                         bOK &=
    2159           2 :                             VSIFPrintfL(fpCSVT, "%s", "JSonInteger64List") > 0;
    2160           2 :                         break;
    2161           2 :                     case OFTRealList:
    2162           2 :                         bOK &= VSIFPrintfL(fpCSVT, "%s", "JSonRealList") > 0;
    2163           2 :                         break;
    2164          36 :                     default:
    2165          36 :                         bOK &= VSIFPrintfL(fpCSVT, "%s", "String") > 0;
    2166          36 :                         break;
    2167             :                 }
    2168             : 
    2169         177 :                 if (nWidth != 0)
    2170             :                 {
    2171          22 :                     if (nPrecision != 0)
    2172           9 :                         bOK &= VSIFPrintfL(fpCSVT, "(%d.%d)", nWidth,
    2173           9 :                                            nPrecision) > 0;
    2174             :                     else
    2175          13 :                         bOK &= VSIFPrintfL(fpCSVT, "(%d)", nWidth) > 0;
    2176             :                 }
    2177             :             }
    2178             :         }
    2179             : 
    2180         164 :         if (bUseCRLF)
    2181             :         {
    2182           1 :             if (fpCSV)
    2183           1 :                 bOK &= VSIFPutcL(13, fpCSV) > 0;
    2184           1 :             if (fpCSVT)
    2185           0 :                 bOK &= VSIFPutcL(13, fpCSVT) > 0;
    2186             :         }
    2187         164 :         if (fpCSV)
    2188         132 :             bOK &= VSIFPutcL('\n', fpCSV) > 0;
    2189         164 :         if (fpCSVT)
    2190          32 :             bOK &= VSIFPutcL('\n', fpCSVT) > 0;
    2191         164 :         if (fpCSVT)
    2192          32 :             VSIFCloseL(fpCSVT);
    2193             :     }
    2194             : 
    2195         132 :     return (!bOK || fpCSV == nullptr) ? OGRERR_FAILURE : OGRERR_NONE;
    2196             : }
    2197             : 
    2198             : /************************************************************************/
    2199             : /*                           ICreateFeature()                            */
    2200             : /************************************************************************/
    2201             : 
    2202         284 : OGRErr OGRCSVLayer::ICreateFeature(OGRFeature *poNewFeature)
    2203             : 
    2204             : {
    2205         284 :     if (!bInWriteMode)
    2206             :     {
    2207           1 :         CPLError(CE_Failure, CPLE_AppDefined,
    2208             :                  "The CreateFeature() operation is not permitted on a "
    2209             :                  "read-only CSV.");
    2210           1 :         return OGRERR_FAILURE;
    2211             :     }
    2212             : 
    2213             :     // If we need rewind, it means that we have just written a feature before
    2214             :     // so there's no point seeking to the end of the file, as we're already
    2215             :     // at the end.
    2216         283 :     bool bNeedSeekEnd = !bNeedRewindBeforeRead;
    2217             : 
    2218         283 :     bNeedRewindBeforeRead = true;
    2219             : 
    2220             :     // Write field names if we haven't written them yet.
    2221             :     // Write .csvt file if needed.
    2222         283 :     if (bNew)
    2223             :     {
    2224         105 :         const OGRErr eErr = WriteHeader();
    2225         105 :         if (eErr != OGRERR_NONE)
    2226           0 :             return eErr;
    2227         105 :         bNeedSeekEnd = false;
    2228             :     }
    2229             : 
    2230         283 :     if (fpCSV == nullptr)
    2231           0 :         return OGRERR_FAILURE;
    2232             : 
    2233         283 :     bool bRet = true;
    2234             : 
    2235             :     // Make sure we are at the end of the file.
    2236         283 :     if (bNeedSeekEnd)
    2237             :     {
    2238          21 :         if (bFirstFeatureAppendedDuringSession)
    2239             :         {
    2240             :             // Add a newline character to the end of the file if necessary.
    2241          21 :             bFirstFeatureAppendedDuringSession = false;
    2242          21 :             bRet &= VSIFSeekL(fpCSV, 0, SEEK_END) >= 0;
    2243          21 :             bRet &= VSIFSeekL(fpCSV, VSIFTellL(fpCSV) - 1, SEEK_SET) >= 0;
    2244          21 :             char chLast = '\0';
    2245          21 :             bRet &= VSIFReadL(&chLast, 1, 1, fpCSV) > 0;
    2246          21 :             bRet &= VSIFSeekL(fpCSV, 0, SEEK_END) >= 0;
    2247          21 :             if (chLast != '\n')
    2248             :             {
    2249           0 :                 if (bUseCRLF)
    2250           0 :                     bRet &= VSIFPutcL(13, fpCSV) != EOF;
    2251           0 :                 bRet &= VSIFPutcL('\n', fpCSV) != EOF;
    2252             :             }
    2253             :         }
    2254             :         else
    2255             :         {
    2256           0 :             bRet &= VSIFSeekL(fpCSV, 0, SEEK_END) >= 0;
    2257             :         }
    2258             :     }
    2259             : 
    2260         283 :     bool bNeedDelimiter = false;
    2261         283 :     bool bEmptyLine = true;
    2262             : 
    2263          92 :     const auto GetWktOptions = [](const OGRGeomFieldDefn *poGeomFieldDefn)
    2264             :     {
    2265          92 :         const auto &sCoordPrec = poGeomFieldDefn->GetCoordinatePrecision();
    2266             : 
    2267          92 :         OGRWktOptions wktOptions;
    2268          92 :         wktOptions.variant = wkbVariantIso;
    2269          92 :         if (sCoordPrec.dfXYResolution != OGRGeomCoordinatePrecision::UNKNOWN)
    2270             :         {
    2271           3 :             wktOptions.format = OGRWktFormat::F;
    2272           3 :             wktOptions.xyPrecision =
    2273           3 :                 OGRGeomCoordinatePrecision::ResolutionToPrecision(
    2274           3 :                     sCoordPrec.dfXYResolution);
    2275             :         }
    2276          92 :         if (sCoordPrec.dfZResolution != OGRGeomCoordinatePrecision::UNKNOWN)
    2277             :         {
    2278           2 :             wktOptions.format = OGRWktFormat::F;
    2279           2 :             wktOptions.zPrecision =
    2280           2 :                 OGRGeomCoordinatePrecision::ResolutionToPrecision(
    2281           2 :                     sCoordPrec.dfZResolution);
    2282             :         }
    2283          92 :         if (sCoordPrec.dfMResolution != OGRGeomCoordinatePrecision::UNKNOWN)
    2284             :         {
    2285           2 :             wktOptions.format = OGRWktFormat::F;
    2286           2 :             wktOptions.mPrecision =
    2287           2 :                 OGRGeomCoordinatePrecision::ResolutionToPrecision(
    2288           2 :                     sCoordPrec.dfMResolution);
    2289             :         }
    2290             : 
    2291          92 :         return wktOptions;
    2292             :     };
    2293             : 
    2294             :     // Write out the geometry.
    2295         283 :     if (eGeometryFormat == OGR_CSV_GEOM_AS_XYZ ||
    2296         281 :         eGeometryFormat == OGR_CSV_GEOM_AS_XY ||
    2297         278 :         eGeometryFormat == OGR_CSV_GEOM_AS_YX)
    2298             :     {
    2299           6 :         const OGRGeometry *poGeom = poNewFeature->GetGeometryRef();
    2300           6 :         if (poGeom && wkbFlatten(poGeom->getGeometryType()) == wkbPoint)
    2301             :         {
    2302           5 :             const auto poGeomFieldDefn = poFeatureDefn->GetGeomFieldDefn(0);
    2303           5 :             const OGRPoint *poPoint = poGeom->toPoint();
    2304           5 :             std::string osCoord;
    2305           5 :             if (eGeometryFormat == OGR_CSV_GEOM_AS_XYZ)
    2306           4 :                 osCoord = OGRMakeWktCoordinate(poPoint->getX(), poPoint->getY(),
    2307             :                                                poPoint->getZ(), 3,
    2308           6 :                                                GetWktOptions(poGeomFieldDefn));
    2309           3 :             else if (eGeometryFormat == OGR_CSV_GEOM_AS_XY)
    2310             :                 osCoord =
    2311           4 :                     OGRMakeWktCoordinate(poPoint->getX(), poPoint->getY(), 0, 2,
    2312           6 :                                          GetWktOptions(poGeomFieldDefn));
    2313             :             else
    2314             :                 osCoord =
    2315           2 :                     OGRMakeWktCoordinate(poPoint->getY(), poPoint->getX(), 0, 2,
    2316           3 :                                          GetWktOptions(poGeomFieldDefn));
    2317             : 
    2318          41 :             for (char &ch : osCoord)
    2319             :             {
    2320          36 :                 if (ch == ' ')
    2321           7 :                     ch = szDelimiter[0];
    2322             :             }
    2323           5 :             bRet &= VSIFPrintfL(fpCSV, "%s", osCoord.c_str()) > 0;
    2324             :         }
    2325             :         else
    2326             :         {
    2327           1 :             bRet &= VSIFPrintfL(fpCSV, "%s", szDelimiter) > 0;
    2328           1 :             if (eGeometryFormat == OGR_CSV_GEOM_AS_XYZ)
    2329           0 :                 bRet &= VSIFPrintfL(fpCSV, "%s", szDelimiter) > 0;
    2330             :         }
    2331           6 :         bEmptyLine = false;
    2332           6 :         bNeedDelimiter = true;
    2333             :     }
    2334         277 :     else if (bHiddenWKTColumn)
    2335             :     {
    2336          74 :         const OGRGeometry *poGeom = poNewFeature->GetGeomFieldRef(0);
    2337          74 :         if (poGeom)
    2338             :         {
    2339          67 :             const auto poGeomFieldDefn = poFeatureDefn->GetGeomFieldDefn(0);
    2340             :             const std::string wkt =
    2341         134 :                 poGeom->exportToWkt(GetWktOptions(poGeomFieldDefn));
    2342          67 :             if (!wkt.empty())
    2343             :             {
    2344          67 :                 bRet &= VSIFWriteL("\"", 1, 1, fpCSV) > 0;
    2345          67 :                 bRet &= VSIFWriteL(wkt.c_str(), wkt.size(), 1, fpCSV) > 0;
    2346          67 :                 bRet &= VSIFWriteL("\"", 1, 1, fpCSV) > 0;
    2347          67 :                 bEmptyLine = false;
    2348             :             }
    2349             :         }
    2350          74 :         bNeedDelimiter = true;
    2351             :     }
    2352             : 
    2353             :     // Write out all the field values.
    2354        1743 :     for (int iField = 0; iField < poFeatureDefn->GetFieldCount(); iField++)
    2355             :     {
    2356        1460 :         char *pszEscaped = nullptr;
    2357             : 
    2358        1460 :         if (bNeedDelimiter)
    2359             :         {
    2360        1257 :             bRet &= VSIFPrintfL(fpCSV, "%s", szDelimiter) > 0;
    2361        1257 :             bEmptyLine = false;
    2362             :         }
    2363        1460 :         bNeedDelimiter = true;
    2364             : 
    2365        1460 :         if (eGeometryFormat == OGR_CSV_GEOM_AS_WKT &&
    2366         530 :             panGeomFieldIndex[iField] >= 0)
    2367             :         {
    2368          24 :             const int iGeom = panGeomFieldIndex[iField];
    2369          24 :             const OGRGeometry *poGeom = poNewFeature->GetGeomFieldRef(iGeom);
    2370          24 :             if (poGeom)
    2371             :             {
    2372             :                 const auto poGeomFieldDefn =
    2373          20 :                     poFeatureDefn->GetGeomFieldDefn(iGeom);
    2374             :                 const std::string wkt =
    2375          40 :                     poGeom->exportToWkt(GetWktOptions(poGeomFieldDefn));
    2376          20 :                 if (!wkt.empty())
    2377             :                 {
    2378             :                     char *pszNew =
    2379          20 :                         static_cast<char *>(CPLMalloc(1 + wkt.size() + 1 + 1));
    2380          20 :                     pszNew[0] = '"';
    2381          20 :                     memcpy(pszNew + 1, wkt.c_str(), wkt.size());
    2382          20 :                     pszNew[1 + wkt.size()] = '"';
    2383          20 :                     pszNew[1 + wkt.size() + 1] = '\0';
    2384          20 :                     CPLFree(pszEscaped);
    2385          20 :                     pszEscaped = pszNew;
    2386             :                 }
    2387             :                 else
    2388             :                 {
    2389           0 :                     CPLFree(pszEscaped);
    2390           0 :                     pszEscaped = CPLStrdup("");
    2391             :                 }
    2392             :             }
    2393             :             else
    2394             :             {
    2395           4 :                 CPLFree(pszEscaped);
    2396           4 :                 pszEscaped = CPLStrdup("");
    2397          24 :             }
    2398             :         }
    2399             :         else
    2400             :         {
    2401             :             const OGRFieldType eType(
    2402        1436 :                 poFeatureDefn->GetFieldDefn(iField)->GetType());
    2403        1436 :             if (eType == OFTReal || eType == OFTInteger ||
    2404             :                 eType == OFTInteger64)
    2405             :             {
    2406         589 :                 if (poFeatureDefn->GetFieldDefn(iField)->GetSubType() ==
    2407         620 :                         OFSTFloat32 &&
    2408          31 :                     poNewFeature->IsFieldSetAndNotNull(iField))
    2409             :                 {
    2410          11 :                     pszEscaped = CPLStrdup(CPLSPrintf(
    2411             :                         "%.8g", poNewFeature->GetFieldAsDouble(iField)));
    2412             :                 }
    2413             :                 else
    2414             :                 {
    2415             :                     pszEscaped =
    2416         578 :                         CPLStrdup(poNewFeature->GetFieldAsString(iField));
    2417             :                 }
    2418             :             }
    2419         847 :             else if (eType == OFTStringList || eType == OFTIntegerList ||
    2420         840 :                      eType == OFTInteger64List || eType == OFTRealList)
    2421             :             {
    2422           9 :                 char *pszJSon = poNewFeature->GetFieldAsSerializedJSon(iField);
    2423           9 :                 if (pszJSon)
    2424             :                 {
    2425           9 :                     pszEscaped = CPLEscapeString(pszJSon, -1,
    2426           9 :                                                  m_eStringQuoting ==
    2427             :                                                          StringQuoting::ALWAYS
    2428             :                                                      ? CPLES_CSV_FORCE_QUOTING
    2429             :                                                      : CPLES_CSV);
    2430             :                 }
    2431             :                 else
    2432             :                 {
    2433           0 :                     pszEscaped = CPLStrdup("");
    2434             :                 }
    2435           9 :                 CPLFree(pszJSon);
    2436             :             }
    2437             :             else
    2438             :             {
    2439         838 :                 const char *pszContent = poNewFeature->GetFieldAsString(iField);
    2440         838 :                 pszEscaped = CPLEscapeString(
    2441             :                     pszContent, -1,
    2442         838 :                     (m_eStringQuoting == StringQuoting::ALWAYS ||
    2443         828 :                      (m_eStringQuoting == StringQuoting::IF_AMBIGUOUS &&
    2444         685 :                       (CPLGetValueType(pszContent) != CPL_VALUE_STRING ||
    2445         563 :                        (pszContent[0] == DIGIT_ZERO && pszContent[1] != '\0' &&
    2446           2 :                         pszContent[1] != '.'))))
    2447             :                         ? CPLES_CSV_FORCE_QUOTING
    2448             :                         : CPLES_CSV);
    2449             :             }
    2450             :         }
    2451        1460 :         if (pszEscaped == nullptr)
    2452             :         {
    2453           0 :             return OGRERR_FAILURE;
    2454             :         }
    2455        1460 :         const size_t nLen = strlen(pszEscaped);
    2456        1460 :         bool bAddDoubleQuote = false;
    2457        1460 :         if (szDelimiter[0] == ' ' && pszEscaped[0] != '"' &&
    2458           2 :             strchr(pszEscaped, ' ') != nullptr)
    2459           1 :             bAddDoubleQuote = true;
    2460        1460 :         if (bAddDoubleQuote)
    2461           1 :             bRet &= VSIFWriteL("\"", 1, 1, fpCSV) > 0;
    2462        1460 :         if (nLen)
    2463             :         {
    2464         908 :             bRet &= VSIFWriteL(pszEscaped, nLen, 1, fpCSV) > 0;
    2465         908 :             bEmptyLine = false;
    2466             :         }
    2467        1460 :         if (bAddDoubleQuote)
    2468           1 :             bRet &= VSIFWriteL("\"", 1, 1, fpCSV) > 0;
    2469        1460 :         CPLFree(pszEscaped);
    2470             :     }
    2471             : 
    2472         283 :     if (bEmptyLine)
    2473           1 :         bRet &= VSIFPrintfL(fpCSV, "\"\"") > 0;
    2474             : 
    2475         283 :     if (bUseCRLF)
    2476           4 :         bRet &= VSIFPutcL(13, fpCSV) != EOF;
    2477         283 :     bRet &= VSIFPutcL('\n', fpCSV) != EOF;
    2478             : 
    2479         283 :     if (nTotalFeatures >= 0)
    2480         263 :         nTotalFeatures++;
    2481             : 
    2482         283 :     return bRet ? OGRERR_NONE : OGRERR_FAILURE;
    2483             : }
    2484             : 
    2485             : /************************************************************************/
    2486             : /*                              SetCRLF()                               */
    2487             : /************************************************************************/
    2488             : 
    2489         132 : void OGRCSVLayer::SetCRLF(bool bNewValue)
    2490             : {
    2491         132 :     bUseCRLF = bNewValue;
    2492         132 : }
    2493             : 
    2494             : /************************************************************************/
    2495             : /*                       SetWriteGeometry()                             */
    2496             : /************************************************************************/
    2497             : 
    2498          50 : void OGRCSVLayer::SetWriteGeometry(OGRwkbGeometryType eGType,
    2499             :                                    OGRCSVGeometryFormat eGeometryFormatIn,
    2500             :                                    const char *pszGeomCol)
    2501             : {
    2502          50 :     eGeometryFormat = eGeometryFormatIn;
    2503          50 :     if (eGeometryFormat == OGR_CSV_GEOM_AS_WKT && eGType != wkbNone)
    2504             :     {
    2505          70 :         OGRGeomFieldDefn oGFld(pszGeomCol, eGType);
    2506          35 :         bHiddenWKTColumn = true;
    2507             :         // We don't use CreateGeomField() since we don't want to generate
    2508             :         // a geometry field in first position, as it confuses applications
    2509             :         // (such as MapServer <= 6.4) that assume that the first regular field
    2510             :         // they add will be at index 0.
    2511          70 :         poFeatureDefn->AddGeomFieldDefn(&oGFld);
    2512             :     }
    2513             :     else
    2514             :     {
    2515          15 :         poFeatureDefn->SetGeomType(eGType);
    2516             :     }
    2517          50 : }
    2518             : 
    2519             : /************************************************************************/
    2520             : /*                          SetCreateCSVT()                             */
    2521             : /************************************************************************/
    2522             : 
    2523          37 : void OGRCSVLayer::SetCreateCSVT(bool bCreateCSVTIn)
    2524             : {
    2525          37 :     bCreateCSVT = bCreateCSVTIn;
    2526          37 : }
    2527             : 
    2528             : /************************************************************************/
    2529             : /*                          SetWriteBOM()                               */
    2530             : /************************************************************************/
    2531             : 
    2532          11 : void OGRCSVLayer::SetWriteBOM(bool bWriteBOMIn)
    2533             : {
    2534          11 :     bWriteBOM = bWriteBOMIn;
    2535          11 : }
    2536             : 
    2537             : /************************************************************************/
    2538             : /*                        GetFeatureCount()                             */
    2539             : /************************************************************************/
    2540             : 
    2541         106 : GIntBig OGRCSVLayer::GetFeatureCount(int bForce)
    2542             : {
    2543         106 :     if (m_poFilterGeom != nullptr || m_poAttrQuery != nullptr)
    2544             :     {
    2545          12 :         return OGRLayer::GetFeatureCount(bForce);
    2546             :     }
    2547             : 
    2548          94 :     if (nTotalFeatures >= 0)
    2549          67 :         return nTotalFeatures;
    2550             : 
    2551          27 :     if (fpCSV == nullptr)
    2552           0 :         return 0;
    2553             : 
    2554          27 :     ResetReading();
    2555             : 
    2556          27 :     if (szDelimiter[0] == '\t' && !bHonourStrings)
    2557             :     {
    2558           1 :         const int nBufSize = 4096;
    2559           1 :         char szBuffer[nBufSize + 1] = {};
    2560             : 
    2561           1 :         nTotalFeatures = 0;
    2562           1 :         bool bLastWasNewLine = false;
    2563             :         while (true)
    2564             :         {
    2565             :             const int nRead =
    2566           1 :                 static_cast<int>(VSIFReadL(szBuffer, 1, nBufSize, fpCSV));
    2567           1 :             szBuffer[nRead] = 0;
    2568           1 :             if (nTotalFeatures == 0 && szBuffer[0] != 13 && szBuffer[0] != 10)
    2569           1 :                 nTotalFeatures = 1;
    2570        1061 :             for (int i = 0; i < nRead; i++)
    2571             :             {
    2572        1060 :                 if (szBuffer[i] == 13 || szBuffer[i] == 10)
    2573             :                 {
    2574          10 :                     bLastWasNewLine = true;
    2575             :                 }
    2576        1050 :                 else if (bLastWasNewLine)
    2577             :                 {
    2578           9 :                     nTotalFeatures++;
    2579           9 :                     bLastWasNewLine = false;
    2580             :                 }
    2581             :             }
    2582             : 
    2583           1 :             if (nRead < nBufSize)
    2584           1 :                 break;
    2585           1 :         }
    2586             :     }
    2587             :     else
    2588             :     {
    2589          26 :         nTotalFeatures = 0;
    2590             :         while (true)
    2591             :         {
    2592         811 :             char **papszTokens = GetNextLineTokens();
    2593         811 :             if (papszTokens == nullptr)
    2594          26 :                 break;
    2595             : 
    2596         785 :             nTotalFeatures++;
    2597             : 
    2598         785 :             CSLDestroy(papszTokens);
    2599         785 :         }
    2600             :     }
    2601             : 
    2602          27 :     ResetReading();
    2603             : 
    2604          27 :     return nTotalFeatures;
    2605             : }
    2606             : 
    2607             : /************************************************************************/
    2608             : /*                          SyncToDisk()                                */
    2609             : /************************************************************************/
    2610             : 
    2611         243 : OGRErr OGRCSVLayer::SyncToDisk()
    2612             : {
    2613         243 :     if (bInWriteMode && fpCSV != nullptr)
    2614             :     {
    2615         219 :         if (VSIFFlushL(fpCSV) != 0)
    2616           0 :             return OGRERR_FAILURE;
    2617             :     }
    2618         243 :     return OGRERR_NONE;
    2619             : }

Generated by: LCOV version 1.14