Line data Source code
1 : /******************************************************************************
2 : *
3 : * Project: CSV Translator
4 : * Purpose: Implements OGRCSVDataSource class
5 : * Author: Frank Warmerdam, warmerdam@pobox.com
6 : *
7 : ******************************************************************************
8 : * Copyright (c) 2004, Frank Warmerdam <warmerdam@pobox.com>
9 : * Copyright (c) 2008-2013, 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 <cstring>
19 : #include <string>
20 : #include <algorithm>
21 :
22 : #include "cpl_conv.h"
23 : #include "cpl_csv.h"
24 : #include "cpl_error.h"
25 : #include "cpl_string.h"
26 : #include "cpl_vsi.h"
27 : #include "cpl_vsi_virtual.h"
28 : #include "ogr_core.h"
29 : #include "ogr_feature.h"
30 : #include "ogr_geometry.h"
31 : #include "ogr_spatialref.h"
32 : #include "ogreditablelayer.h"
33 : #include "ogrsf_frmts.h"
34 : #include "ogr_schema_override.h"
35 :
36 : /************************************************************************/
37 : /* OGRCSVEditableLayerSynchronizer */
38 : /************************************************************************/
39 :
40 : class OGRCSVEditableLayerSynchronizer final
41 : : public IOGREditableLayerSynchronizer
42 : {
43 : OGRCSVLayer *m_poCSVLayer = nullptr;
44 : char **m_papszOpenOptions = nullptr;
45 :
46 : CPL_DISALLOW_COPY_ASSIGN(OGRCSVEditableLayerSynchronizer)
47 :
48 : public:
49 231 : OGRCSVEditableLayerSynchronizer(OGRCSVLayer *poCSVLayer,
50 : CSLConstList papszOpenOptions)
51 231 : : m_poCSVLayer(poCSVLayer),
52 231 : m_papszOpenOptions(CSLDuplicate(papszOpenOptions))
53 : {
54 231 : }
55 :
56 : ~OGRCSVEditableLayerSynchronizer() override;
57 :
58 : virtual OGRErr EditableSyncToDisk(OGRLayer *poEditableLayer,
59 : OGRLayer **ppoDecoratedLayer) override;
60 :
61 18 : std::vector<std::string> GetFileList()
62 : {
63 18 : return m_poCSVLayer->GetFileList();
64 : }
65 : };
66 :
67 : /************************************************************************/
68 : /* ~OGRCSVEditableLayerSynchronizer() */
69 : /************************************************************************/
70 :
71 462 : OGRCSVEditableLayerSynchronizer::~OGRCSVEditableLayerSynchronizer()
72 : {
73 231 : CSLDestroy(m_papszOpenOptions);
74 462 : }
75 :
76 : /************************************************************************/
77 : /* EditableSyncToDisk() */
78 : /************************************************************************/
79 :
80 9 : OGRErr OGRCSVEditableLayerSynchronizer::EditableSyncToDisk(
81 : OGRLayer *poEditableLayer, OGRLayer **ppoDecoratedLayer)
82 : {
83 9 : CPLAssert(m_poCSVLayer == *ppoDecoratedLayer);
84 :
85 9 : GDALDataset *poDS = m_poCSVLayer->GetDataset();
86 18 : const CPLString osLayerName(m_poCSVLayer->GetName());
87 18 : const CPLString osFilename(m_poCSVLayer->GetFilename());
88 9 : const bool bCreateCSVT = m_poCSVLayer->GetCreateCSVT();
89 18 : const CPLString osCSVTFilename(CPLResetExtensionSafe(osFilename, "csvt"));
90 : VSIStatBufL sStatBuf;
91 9 : const bool bHasCSVT = VSIStatL(osCSVTFilename, &sStatBuf) == 0;
92 18 : CPLString osTmpFilename(osFilename);
93 18 : CPLString osTmpCSVTFilename(osFilename);
94 9 : if (VSIStatL(osFilename, &sStatBuf) == 0)
95 : {
96 9 : osTmpFilename += "_ogr_tmp.csv";
97 9 : osTmpCSVTFilename += "_ogr_tmp.csvt";
98 : }
99 9 : const char chDelimiter = m_poCSVLayer->GetDelimiter();
100 : OGRCSVLayer *poCSVTmpLayer = new OGRCSVLayer(
101 9 : poDS, osLayerName, nullptr, -1, osTmpFilename, true, true, chDelimiter);
102 9 : poCSVTmpLayer->BuildFeatureDefn(nullptr, nullptr, m_papszOpenOptions);
103 9 : poCSVTmpLayer->SetCRLF(m_poCSVLayer->GetCRLF());
104 9 : poCSVTmpLayer->SetCreateCSVT(bCreateCSVT || bHasCSVT);
105 9 : poCSVTmpLayer->SetWriteBOM(m_poCSVLayer->GetWriteBOM());
106 9 : poCSVTmpLayer->SetStringQuoting(m_poCSVLayer->GetStringQuoting());
107 :
108 9 : if (m_poCSVLayer->GetGeometryFormat() == OGR_CSV_GEOM_AS_WKT)
109 5 : poCSVTmpLayer->SetWriteGeometry(wkbNone, OGR_CSV_GEOM_AS_WKT, nullptr);
110 :
111 : const bool bKeepGeomColmuns =
112 9 : CPLFetchBool(m_papszOpenOptions, "KEEP_GEOM_COLUMNS", true);
113 :
114 9 : OGRErr eErr = OGRERR_NONE;
115 9 : OGRFeatureDefn *poEditableFDefn = poEditableLayer->GetLayerDefn();
116 31 : for (int i = 0; eErr == OGRERR_NONE && i < poEditableFDefn->GetFieldCount();
117 : i++)
118 : {
119 44 : OGRFieldDefn oFieldDefn(poEditableFDefn->GetFieldDefn(i));
120 22 : int iGeomFieldIdx = 0;
121 70 : if ((EQUAL(oFieldDefn.GetNameRef(), "WKT") &&
122 38 : (iGeomFieldIdx = poEditableFDefn->GetGeomFieldIndex("")) >= 0) ||
123 32 : (bKeepGeomColmuns &&
124 16 : (iGeomFieldIdx = poEditableFDefn->GetGeomFieldIndex(
125 38 : (std::string("geom_") + oFieldDefn.GetNameRef()).c_str())) >=
126 : 0))
127 : {
128 : OGRGeomFieldDefn oGeomFieldDefn(
129 5 : poEditableFDefn->GetGeomFieldDefn(iGeomFieldIdx));
130 5 : eErr = poCSVTmpLayer->CreateGeomField(&oGeomFieldDefn);
131 : }
132 : else
133 : {
134 17 : eErr = poCSVTmpLayer->CreateField(&oFieldDefn);
135 : }
136 : }
137 :
138 12 : const bool bHasXY = !m_poCSVLayer->GetXField().empty() &&
139 3 : !m_poCSVLayer->GetYField().empty();
140 9 : const bool bHasZ = !m_poCSVLayer->GetZField().empty();
141 9 : if (bHasXY && !bKeepGeomColmuns)
142 : {
143 4 : if (poCSVTmpLayer->GetLayerDefn()->GetFieldIndex(
144 4 : m_poCSVLayer->GetXField()) < 0)
145 : {
146 4 : OGRFieldDefn oFieldDefn(m_poCSVLayer->GetXField(), OFTReal);
147 2 : if (eErr == OGRERR_NONE)
148 2 : eErr = poCSVTmpLayer->CreateField(&oFieldDefn);
149 : }
150 4 : if (poCSVTmpLayer->GetLayerDefn()->GetFieldIndex(
151 4 : m_poCSVLayer->GetYField()) < 0)
152 : {
153 4 : OGRFieldDefn oFieldDefn(m_poCSVLayer->GetYField(), OFTReal);
154 2 : if (eErr == OGRERR_NONE)
155 2 : eErr = poCSVTmpLayer->CreateField(&oFieldDefn);
156 : }
157 3 : if (bHasZ && poCSVTmpLayer->GetLayerDefn()->GetFieldIndex(
158 1 : m_poCSVLayer->GetZField()) < 0)
159 : {
160 2 : OGRFieldDefn oFieldDefn(m_poCSVLayer->GetZField(), OFTReal);
161 1 : if (eErr == OGRERR_NONE)
162 1 : eErr = poCSVTmpLayer->CreateField(&oFieldDefn);
163 : }
164 : }
165 :
166 9 : int nFirstGeomColIdx = 0;
167 9 : if (m_poCSVLayer->HasHiddenWKTColumn())
168 : {
169 2 : poCSVTmpLayer->SetWriteGeometry(
170 1 : poEditableFDefn->GetGeomFieldDefn(0)->GetType(),
171 : OGR_CSV_GEOM_AS_WKT,
172 1 : poEditableFDefn->GetGeomFieldDefn(0)->GetNameRef());
173 1 : nFirstGeomColIdx = 1;
174 : }
175 :
176 9 : if (!(poEditableFDefn->GetGeomFieldCount() == 1 && bHasXY))
177 : {
178 12 : for (int i = nFirstGeomColIdx;
179 12 : eErr == OGRERR_NONE && i < poEditableFDefn->GetGeomFieldCount();
180 : i++)
181 : {
182 : OGRGeomFieldDefn oGeomFieldDefn(
183 6 : poEditableFDefn->GetGeomFieldDefn(i));
184 12 : if (poCSVTmpLayer->GetLayerDefn()->GetGeomFieldIndex(
185 12 : oGeomFieldDefn.GetNameRef()) >= 0)
186 5 : continue;
187 1 : eErr = poCSVTmpLayer->CreateGeomField(&oGeomFieldDefn);
188 : }
189 : }
190 :
191 9 : poEditableLayer->ResetReading();
192 :
193 : // Disable all filters.
194 9 : const char *pszQueryStringConst = poEditableLayer->GetAttrQueryString();
195 : char *pszQueryStringBak =
196 9 : pszQueryStringConst ? CPLStrdup(pszQueryStringConst) : nullptr;
197 9 : poEditableLayer->SetAttributeFilter(nullptr);
198 :
199 9 : const int iFilterGeomIndexBak = poEditableLayer->GetGeomFieldFilter();
200 9 : OGRGeometry *poFilterGeomBak = poEditableLayer->GetSpatialFilter();
201 9 : if (poFilterGeomBak)
202 1 : poFilterGeomBak = poFilterGeomBak->clone();
203 9 : poEditableLayer->SetSpatialFilter(nullptr);
204 :
205 : auto aoMapSrcToTargetIdx =
206 : poCSVTmpLayer->GetLayerDefn()->ComputeMapForSetFrom(
207 18 : poEditableLayer->GetLayerDefn(), true);
208 9 : aoMapSrcToTargetIdx.push_back(
209 9 : -1); // add dummy entry to be sure that .data() is valid
210 :
211 21 : for (auto &&poFeature : poEditableLayer)
212 : {
213 12 : if (eErr != OGRERR_NONE)
214 0 : break;
215 : OGRFeature *poNewFeature =
216 12 : new OGRFeature(poCSVTmpLayer->GetLayerDefn());
217 12 : poNewFeature->SetFrom(poFeature.get(), aoMapSrcToTargetIdx.data(),
218 : true);
219 12 : if (bHasXY)
220 : {
221 3 : OGRGeometry *poGeom = poFeature->GetGeometryRef();
222 6 : if (poGeom != nullptr &&
223 3 : wkbFlatten(poGeom->getGeometryType()) == wkbPoint)
224 : {
225 3 : auto poPoint = poGeom->toPoint();
226 3 : poNewFeature->SetField(m_poCSVLayer->GetXField(),
227 : poPoint->getX());
228 3 : poNewFeature->SetField(m_poCSVLayer->GetYField(),
229 : poPoint->getY());
230 3 : if (bHasZ)
231 : {
232 1 : poNewFeature->SetField(m_poCSVLayer->GetZField(),
233 : poPoint->getZ());
234 : }
235 : }
236 : }
237 12 : eErr = poCSVTmpLayer->CreateFeature(poNewFeature);
238 12 : delete poNewFeature;
239 : }
240 9 : delete poCSVTmpLayer;
241 :
242 : // Restore filters.
243 9 : poEditableLayer->SetAttributeFilter(pszQueryStringBak);
244 9 : CPLFree(pszQueryStringBak);
245 9 : poEditableLayer->SetSpatialFilter(iFilterGeomIndexBak, poFilterGeomBak);
246 9 : delete poFilterGeomBak;
247 :
248 9 : if (eErr != OGRERR_NONE)
249 : {
250 0 : CPLError(CE_Failure, CPLE_AppDefined, "Error while creating %s",
251 : osTmpFilename.c_str());
252 0 : VSIUnlink(osTmpFilename);
253 0 : VSIUnlink(CPLResetExtensionSafe(osTmpFilename, "csvt").c_str());
254 0 : return eErr;
255 : }
256 :
257 9 : delete m_poCSVLayer;
258 :
259 9 : if (osFilename != osTmpFilename)
260 : {
261 9 : const CPLString osTmpOriFilename(osFilename + ".ogr_bak");
262 9 : const CPLString osTmpOriCSVTFilename(osCSVTFilename + ".ogr_bak");
263 18 : if (VSIRename(osFilename, osTmpOriFilename) != 0 ||
264 4 : (bHasCSVT &&
265 4 : VSIRename(osCSVTFilename, osTmpOriCSVTFilename) != 0) ||
266 22 : VSIRename(osTmpFilename, osFilename) != 0 ||
267 4 : (bHasCSVT && VSIRename(osTmpCSVTFilename, osCSVTFilename) != 0))
268 : {
269 0 : CPLError(CE_Failure, CPLE_AppDefined, "Cannot rename files");
270 0 : *ppoDecoratedLayer = nullptr;
271 0 : m_poCSVLayer = nullptr;
272 0 : return OGRERR_FAILURE;
273 : }
274 9 : VSIUnlink(osTmpOriFilename);
275 9 : if (bHasCSVT)
276 4 : VSIUnlink(osTmpOriCSVTFilename);
277 : }
278 :
279 9 : VSILFILE *fp = VSIFOpenL(osFilename, "rb+");
280 9 : if (fp == nullptr)
281 : {
282 0 : CPLError(CE_Failure, CPLE_AppDefined, "Cannot reopen updated %s",
283 : osFilename.c_str());
284 0 : *ppoDecoratedLayer = nullptr;
285 0 : m_poCSVLayer = nullptr;
286 0 : return OGRERR_FAILURE;
287 : }
288 :
289 9 : m_poCSVLayer =
290 : new OGRCSVLayer(poDS, osLayerName, fp, -1, osFilename, false, /* new */
291 : true, /* update */
292 9 : chDelimiter);
293 9 : m_poCSVLayer->BuildFeatureDefn(nullptr, nullptr, m_papszOpenOptions);
294 9 : *ppoDecoratedLayer = m_poCSVLayer;
295 :
296 9 : return OGRERR_NONE;
297 : }
298 :
299 : /************************************************************************/
300 : /* OGRCSVEditableLayer */
301 : /************************************************************************/
302 :
303 : class OGRCSVEditableLayer final : public IOGRCSVLayer, public OGREditableLayer
304 : {
305 : std::set<CPLString> m_oSetFields{};
306 :
307 : public:
308 : OGRCSVEditableLayer(OGRCSVLayer *poCSVLayer, CSLConstList papszOpenOptions);
309 :
310 362 : OGRLayer *GetLayer() override
311 : {
312 362 : return this;
313 : }
314 :
315 18 : std::vector<std::string> GetFileList() override
316 : {
317 : return cpl::down_cast<OGRCSVEditableLayerSynchronizer *>(
318 : m_poSynchronizer)
319 18 : ->GetFileList();
320 : }
321 :
322 : virtual OGRErr CreateField(const OGRFieldDefn *poField,
323 : int bApproxOK = TRUE) override;
324 : OGRErr DeleteField(int iField) override;
325 : virtual OGRErr AlterFieldDefn(int iField, OGRFieldDefn *poNewFieldDefn,
326 : int nFlagsIn) override;
327 : GIntBig GetFeatureCount(int bForce = TRUE) override;
328 : };
329 :
330 : /************************************************************************/
331 : /* OGRCSVEditableLayer() */
332 : /************************************************************************/
333 :
334 231 : OGRCSVEditableLayer::OGRCSVEditableLayer(OGRCSVLayer *poCSVLayer,
335 231 : CSLConstList papszOpenOptions)
336 : : OGREditableLayer(
337 : poCSVLayer, true,
338 231 : new OGRCSVEditableLayerSynchronizer(poCSVLayer, papszOpenOptions),
339 462 : true)
340 : {
341 231 : SetSupportsCreateGeomField(true);
342 231 : SetSupportsCurveGeometries(true);
343 231 : }
344 :
345 : /************************************************************************/
346 : /* CreateField() */
347 : /************************************************************************/
348 :
349 485 : OGRErr OGRCSVEditableLayer::CreateField(const OGRFieldDefn *poNewField,
350 : int bApproxOK)
351 :
352 : {
353 485 : if (m_poEditableFeatureDefn->GetFieldCount() >= 10000)
354 : {
355 0 : CPLError(CE_Failure, CPLE_AppDefined, "Limiting to 10000 fields");
356 0 : return OGRERR_FAILURE;
357 : }
358 :
359 485 : if (m_oSetFields.empty())
360 : {
361 121 : for (int i = 0; i < m_poEditableFeatureDefn->GetFieldCount(); i++)
362 : {
363 : m_oSetFields.insert(
364 8 : CPLString(
365 4 : m_poEditableFeatureDefn->GetFieldDefn(i)->GetNameRef())
366 8 : .toupper());
367 : }
368 : }
369 :
370 970 : const OGRCSVCreateFieldAction eAction = OGRCSVLayer::PreCreateField(
371 485 : m_poEditableFeatureDefn, m_oSetFields, poNewField, bApproxOK);
372 485 : if (eAction == CREATE_FIELD_DO_NOTHING)
373 0 : return OGRERR_NONE;
374 485 : if (eAction == CREATE_FIELD_ERROR)
375 1 : return OGRERR_FAILURE;
376 484 : OGRErr eErr = OGREditableLayer::CreateField(poNewField, bApproxOK);
377 484 : if (eErr == OGRERR_NONE)
378 : {
379 484 : m_oSetFields.insert(CPLString(poNewField->GetNameRef()).toupper());
380 : }
381 484 : return eErr;
382 : }
383 :
384 3 : OGRErr OGRCSVEditableLayer::DeleteField(int iField)
385 : {
386 3 : m_oSetFields.clear();
387 3 : return OGREditableLayer::DeleteField(iField);
388 : }
389 :
390 2 : OGRErr OGRCSVEditableLayer::AlterFieldDefn(int iField,
391 : OGRFieldDefn *poNewFieldDefn,
392 : int nFlagsIn)
393 : {
394 2 : m_oSetFields.clear();
395 2 : return OGREditableLayer::AlterFieldDefn(iField, poNewFieldDefn, nFlagsIn);
396 : }
397 :
398 : /************************************************************************/
399 : /* GetFeatureCount() */
400 : /************************************************************************/
401 :
402 28 : GIntBig OGRCSVEditableLayer::GetFeatureCount(int bForce)
403 : {
404 28 : const GIntBig nRet = OGREditableLayer::GetFeatureCount(bForce);
405 28 : if (m_poDecoratedLayer != nullptr && m_nNextFID <= 0)
406 : {
407 : const GIntBig nTotalFeatureCount =
408 8 : static_cast<OGRCSVLayer *>(m_poDecoratedLayer)
409 4 : ->GetTotalFeatureCount();
410 4 : if (nTotalFeatureCount >= 0)
411 3 : SetNextFID(nTotalFeatureCount + 1);
412 : }
413 28 : return nRet;
414 : }
415 :
416 : /************************************************************************/
417 : /* OGRCSVDataSource() */
418 : /************************************************************************/
419 :
420 : OGRCSVDataSource::OGRCSVDataSource() = default;
421 :
422 : /************************************************************************/
423 : /* ~OGRCSVDataSource() */
424 : /************************************************************************/
425 :
426 2780 : OGRCSVDataSource::~OGRCSVDataSource()
427 :
428 : {
429 1390 : m_apoLayers.clear();
430 :
431 1390 : if (bUpdate)
432 272 : OGRCSVDriverRemoveFromMap(pszName, this);
433 :
434 1390 : CPLFree(pszName);
435 2780 : }
436 :
437 : /************************************************************************/
438 : /* TestCapability() */
439 : /************************************************************************/
440 :
441 234 : int OGRCSVDataSource::TestCapability(const char *pszCap) const
442 :
443 : {
444 234 : if (EQUAL(pszCap, ODsCCreateLayer))
445 75 : return bUpdate;
446 159 : else if (EQUAL(pszCap, ODsCDeleteLayer))
447 19 : return bUpdate;
448 140 : else if (EQUAL(pszCap, ODsCCreateGeomFieldAfterCreateLayer))
449 43 : return bUpdate && bEnableGeometryFields;
450 97 : else if (EQUAL(pszCap, ODsCCurveGeometries))
451 3 : return TRUE;
452 94 : else if (EQUAL(pszCap, ODsCMeasuredGeometries))
453 3 : return TRUE;
454 91 : else if (EQUAL(pszCap, ODsCZGeometries))
455 2 : return TRUE;
456 89 : else if (EQUAL(pszCap, ODsCRandomLayerWrite))
457 0 : return bUpdate;
458 : else
459 89 : return FALSE;
460 : }
461 :
462 : /************************************************************************/
463 : /* GetLayer() */
464 : /************************************************************************/
465 :
466 985 : const OGRLayer *OGRCSVDataSource::GetLayer(int iLayer) const
467 :
468 : {
469 985 : if (iLayer < 0 || iLayer >= static_cast<int>(m_apoLayers.size()))
470 2 : return nullptr;
471 :
472 983 : return m_apoLayers[iLayer]->GetLayer();
473 : }
474 :
475 : /************************************************************************/
476 : /* GetRealExtension() */
477 : /************************************************************************/
478 :
479 8548 : CPLString OGRCSVDataSource::GetRealExtension(CPLString osFilename)
480 : {
481 17096 : CPLString osExt = CPLGetExtensionSafe(osFilename);
482 8548 : if (STARTS_WITH(osFilename, "/vsigzip/") && EQUAL(osExt, "gz"))
483 : {
484 14 : if (osFilename.size() > 7 &&
485 7 : EQUAL(osFilename + osFilename.size() - 7, ".csv.gz"))
486 0 : return "csv";
487 14 : else if (osFilename.size() > 7 &&
488 7 : EQUAL(osFilename + osFilename.size() - 7, ".tsv.gz"))
489 0 : return "tsv";
490 14 : else if (osFilename.size() > 7 &&
491 7 : EQUAL(osFilename + osFilename.size() - 7, ".psv.gz"))
492 0 : return "psv";
493 : }
494 8548 : return osExt;
495 : }
496 :
497 : /************************************************************************/
498 : /* Open() */
499 : /************************************************************************/
500 :
501 1313 : bool OGRCSVDataSource::Open(const char *pszFilename, bool bUpdateIn,
502 : bool bForceOpen, CSLConstList papszOpenOptionsIn,
503 : bool bSingleDriver)
504 :
505 : {
506 1313 : pszName = CPLStrdup(pszFilename);
507 1313 : bUpdate = bUpdateIn;
508 :
509 1313 : if (bUpdate && bForceOpen && EQUAL(pszFilename, "/vsistdout/"))
510 1 : return TRUE;
511 :
512 : // For writable /vsizip/, do nothing more.
513 1312 : if (bUpdate && bForceOpen && STARTS_WITH(pszFilename, "/vsizip/"))
514 0 : return TRUE;
515 :
516 2624 : CPLString osFilename(pszFilename);
517 2624 : const CPLString osBaseFilename = CPLGetFilename(pszFilename);
518 2624 : const CPLString osExt = GetRealExtension(osFilename);
519 :
520 1312 : bool bUSGeonamesFile = false;
521 1312 : if (STARTS_WITH_CI(osFilename, "CSV:"))
522 : {
523 1 : bSingleDriver = true;
524 1 : osFilename = osFilename.substr(strlen("CSV:"));
525 : }
526 :
527 : // Those are *not* real .XLS files, but text file with tab as column
528 : // separator.
529 1312 : if (EQUAL(osBaseFilename, "NfdcFacilities.xls") ||
530 1312 : EQUAL(osBaseFilename, "NfdcRunways.xls") ||
531 3936 : EQUAL(osBaseFilename, "NfdcRemarks.xls") ||
532 1312 : EQUAL(osBaseFilename, "NfdcSchedules.xls"))
533 : {
534 0 : if (bUpdate)
535 0 : return FALSE;
536 0 : bSingleDriver = true;
537 : }
538 1312 : else if ((STARTS_WITH_CI(osBaseFilename, "NationalFile_") ||
539 1312 : STARTS_WITH_CI(osBaseFilename, "POP_PLACES_") ||
540 1312 : STARTS_WITH_CI(osBaseFilename, "HIST_FEATURES_") ||
541 1312 : STARTS_WITH_CI(osBaseFilename, "US_CONCISE_") ||
542 1312 : STARTS_WITH_CI(osBaseFilename, "AllNames_") ||
543 1312 : STARTS_WITH_CI(osBaseFilename, "Feature_Description_History_") ||
544 1312 : STARTS_WITH_CI(osBaseFilename, "ANTARCTICA_") ||
545 1312 : STARTS_WITH_CI(osBaseFilename, "GOVT_UNITS_") ||
546 1312 : STARTS_WITH_CI(osBaseFilename, "NationalFedCodes_") ||
547 1312 : STARTS_WITH_CI(osBaseFilename, "AllStates_") ||
548 2624 : STARTS_WITH_CI(osBaseFilename, "AllStatesFedCodes_") ||
549 1312 : (osBaseFilename.size() > 2 &&
550 2598 : STARTS_WITH_CI(osBaseFilename + 2, "_Features_")) ||
551 1312 : (osBaseFilename.size() > 2 &&
552 2624 : STARTS_WITH_CI(osBaseFilename + 2, "_FedCodes_"))) &&
553 0 : (EQUAL(osExt, "txt") || EQUAL(osExt, "zip")))
554 : {
555 0 : if (bUpdate)
556 0 : return FALSE;
557 0 : bSingleDriver = true;
558 0 : bUSGeonamesFile = true;
559 :
560 0 : if (EQUAL(osExt, "zip") && strstr(osFilename, "/vsizip/") == nullptr)
561 : {
562 0 : osFilename = "/vsizip/" + osFilename;
563 : }
564 : }
565 2623 : else if (EQUAL(osBaseFilename, "allCountries.txt") ||
566 1311 : EQUAL(osBaseFilename, "allCountries.zip"))
567 : {
568 1 : if (bUpdate)
569 0 : return FALSE;
570 1 : bSingleDriver = true;
571 :
572 1 : if (EQUAL(osExt, "zip") && strstr(osFilename, "/vsizip/") == nullptr)
573 : {
574 0 : osFilename = "/vsizip/" + osFilename;
575 : }
576 : }
577 :
578 : // Determine what sort of object this is.
579 : VSIStatBufL sStatBuf;
580 :
581 1312 : if (VSIStatExL(osFilename, &sStatBuf, VSI_STAT_NATURE_FLAG) != 0)
582 0 : return FALSE;
583 :
584 : // Is this a single CSV file?
585 1730 : if (VSI_ISREG(sStatBuf.st_mode) &&
586 418 : (bSingleDriver || EQUAL(osExt, "csv") || EQUAL(osExt, "tsv") ||
587 2 : EQUAL(osExt, "psv")))
588 : {
589 510 : if (EQUAL(CPLGetFilename(osFilename), "NfdcFacilities.xls"))
590 : {
591 0 : return OpenTable(osFilename, papszOpenOptionsIn, "ARP");
592 : }
593 510 : else if (EQUAL(CPLGetFilename(osFilename), "NfdcRunways.xls"))
594 : {
595 0 : OpenTable(osFilename, papszOpenOptionsIn, "BaseEndPhysical");
596 0 : OpenTable(osFilename, papszOpenOptionsIn, "BaseEndDisplaced");
597 0 : OpenTable(osFilename, papszOpenOptionsIn, "ReciprocalEndPhysical");
598 0 : OpenTable(osFilename, papszOpenOptionsIn, "ReciprocalEndDisplaced");
599 0 : return !m_apoLayers.empty();
600 : }
601 510 : else if (bUSGeonamesFile)
602 : {
603 : // GNIS specific.
604 0 : if (STARTS_WITH_CI(osBaseFilename, "NationalFedCodes_") ||
605 0 : STARTS_WITH_CI(osBaseFilename, "AllStatesFedCodes_") ||
606 0 : STARTS_WITH_CI(osBaseFilename, "ANTARCTICA_") ||
607 0 : (osBaseFilename.size() > 2 &&
608 0 : STARTS_WITH_CI(osBaseFilename + 2, "_FedCodes_")))
609 : {
610 0 : OpenTable(osFilename, papszOpenOptionsIn, nullptr, "PRIMARY");
611 : }
612 0 : else if (STARTS_WITH_CI(osBaseFilename, "GOVT_UNITS_") ||
613 0 : STARTS_WITH_CI(osBaseFilename,
614 : "Feature_Description_History_"))
615 : {
616 0 : OpenTable(osFilename, papszOpenOptionsIn, nullptr, "");
617 : }
618 : else
619 : {
620 0 : OpenTable(osFilename, papszOpenOptionsIn, nullptr, "PRIM");
621 0 : OpenTable(osFilename, papszOpenOptionsIn, nullptr, "SOURCE");
622 : }
623 0 : return !m_apoLayers.empty();
624 : }
625 :
626 510 : return OpenTable(osFilename, papszOpenOptionsIn);
627 : }
628 :
629 : // Is this a single a ZIP file with only a CSV file inside?
630 807 : if (STARTS_WITH(osFilename, "/vsizip/") && EQUAL(osExt, "zip") &&
631 5 : VSI_ISREG(sStatBuf.st_mode))
632 : {
633 1 : char **papszFiles = VSIReadDir(osFilename);
634 2 : if (CSLCount(papszFiles) != 1 ||
635 2 : !EQUAL(CPLGetExtensionSafe(papszFiles[0]).c_str(), "CSV"))
636 : {
637 1 : CSLDestroy(papszFiles);
638 1 : return FALSE;
639 : }
640 0 : osFilename = CPLFormFilenameSafe(osFilename, papszFiles[0], nullptr);
641 0 : CSLDestroy(papszFiles);
642 0 : return OpenTable(osFilename, papszOpenOptionsIn);
643 : }
644 :
645 : // Otherwise it has to be a directory.
646 801 : if (!VSI_ISDIR(sStatBuf.st_mode))
647 0 : return FALSE;
648 :
649 : // Scan through for entries ending in .csv.
650 801 : int nNotCSVCount = 0;
651 801 : const CPLStringList aosFilenames(VSIReadDir(osFilename));
652 :
653 26922 : for (int i = 0; i < aosFilenames.size(); i++)
654 : {
655 26121 : if (EQUAL(aosFilenames[i], ".") || EQUAL(aosFilenames[i], ".."))
656 25973 : continue;
657 :
658 25345 : const std::string osThisExt = CPLGetExtensionSafe(aosFilenames[i]);
659 25345 : if (EQUAL(osThisExt.c_str(), "csvt") || EQUAL(osThisExt.c_str(), "prj"))
660 94 : continue;
661 :
662 : const CPLString oSubFilename =
663 25251 : CPLFormFilenameSafe(osFilename, aosFilenames[i], nullptr);
664 50502 : if (VSIStatL(oSubFilename, &sStatBuf) != 0 ||
665 25251 : !VSI_ISREG(sStatBuf.st_mode))
666 : {
667 168 : nNotCSVCount++;
668 168 : continue;
669 : }
670 :
671 25083 : if (EQUAL(osThisExt.c_str(), "csv"))
672 : {
673 148 : if (!OpenTable(oSubFilename, papszOpenOptionsIn))
674 : {
675 0 : CPLDebug("CSV", "Cannot open %s", oSubFilename.c_str());
676 0 : nNotCSVCount++;
677 0 : continue;
678 : }
679 : }
680 : // GNIS specific.
681 24935 : else if (strlen(aosFilenames[i]) > 2 &&
682 24935 : STARTS_WITH_CI(aosFilenames[i] + 2, "_Features_") &&
683 0 : EQUAL(osThisExt.c_str(), "txt"))
684 : {
685 : bool bRet =
686 0 : OpenTable(oSubFilename, papszOpenOptionsIn, nullptr, "PRIM");
687 0 : bRet |=
688 0 : OpenTable(oSubFilename, papszOpenOptionsIn, nullptr, "SOURCE");
689 0 : if (!bRet)
690 : {
691 0 : CPLDebug("CSV", "Cannot open %s", oSubFilename.c_str());
692 0 : nNotCSVCount++;
693 0 : continue;
694 : }
695 : }
696 : // GNIS specific.
697 24935 : else if (strlen(aosFilenames[i]) > 2 &&
698 24935 : STARTS_WITH_CI(aosFilenames[i] + 2, "_FedCodes_") &&
699 0 : EQUAL(osThisExt.c_str(), "txt"))
700 : {
701 0 : if (!OpenTable(oSubFilename, papszOpenOptionsIn, nullptr,
702 : "PRIMARY"))
703 : {
704 0 : CPLDebug("CSV", "Cannot open %s", oSubFilename.c_str());
705 0 : nNotCSVCount++;
706 0 : continue;
707 : }
708 : }
709 : else
710 : {
711 24935 : nNotCSVCount++;
712 24935 : continue;
713 : }
714 : }
715 :
716 : // We presume that this is indeed intended to be a CSV
717 : // datasource if over half the files were .csv files.
718 803 : return bForceOpen || nNotCSVCount < GetLayerCount() ||
719 803 : (bSingleDriver && GetLayerCount() > 0);
720 : }
721 :
722 215372 : const std::vector<int> &OGRCSVDataSource::DeletedFieldIndexes() const
723 : {
724 215372 : return m_oDeletedFieldIndexes;
725 : }
726 :
727 : /************************************************************************/
728 : /* DealWithOgrSchemaOpenOption() */
729 : /************************************************************************/
730 570 : bool OGRCSVDataSource::DealWithOgrSchemaOpenOption(
731 : CSLConstList papszOpenOptionsIn)
732 : {
733 : const std::string osFieldsSchemaOverrideParam =
734 1140 : CSLFetchNameValueDef(papszOpenOptionsIn, "OGR_SCHEMA", "");
735 :
736 570 : if (!osFieldsSchemaOverrideParam.empty())
737 : {
738 10 : if (bUpdate)
739 : {
740 0 : CPLError(CE_Failure, CPLE_NotSupported,
741 : "OGR_SCHEMA open option is not supported in update mode.");
742 1 : return false;
743 : }
744 :
745 10 : OGRSchemaOverride oSchemaOverride;
746 10 : const auto nErrorCount = CPLGetErrorCounter();
747 19 : if (!oSchemaOverride.LoadFromJSON(osFieldsSchemaOverrideParam) ||
748 9 : !oSchemaOverride.IsValid())
749 : {
750 1 : if (nErrorCount == CPLGetErrorCounter())
751 : {
752 0 : CPLError(CE_Failure, CPLE_AppDefined,
753 : "Content of OGR_SCHEMA in %s is not valid",
754 : osFieldsSchemaOverrideParam.c_str());
755 : }
756 1 : return false;
757 : }
758 :
759 9 : if (!oSchemaOverride.DefaultApply(
760 10 : this, "CSV", [this](OGRLayer *, int iField)
761 10 : { m_oDeletedFieldIndexes.push_back(iField); }))
762 : {
763 0 : return false;
764 : }
765 : }
766 569 : return true;
767 : }
768 :
769 : /************************************************************************/
770 : /* OpenTable() */
771 : /************************************************************************/
772 :
773 658 : bool OGRCSVDataSource::OpenTable(const char *pszFilename,
774 : CSLConstList papszOpenOptionsIn,
775 : const char *pszNfdcRunwaysGeomField,
776 : const char *pszGeonamesGeomFieldPrefix)
777 :
778 : {
779 : // Open the file.
780 658 : VSILFILE *fp = nullptr;
781 :
782 658 : if (bUpdate)
783 88 : fp = VSIFOpenExL(pszFilename, "rb+", true);
784 : else
785 570 : fp = VSIFOpenExL(pszFilename, "rb", true);
786 658 : if (fp == nullptr)
787 : {
788 0 : CPLError(CE_Warning, CPLE_OpenFailed, "Failed to open %s.",
789 : VSIGetLastErrorMsg());
790 0 : return false;
791 : }
792 :
793 658 : if (!bUpdate && strstr(pszFilename, "/vsigzip/") == nullptr &&
794 570 : strstr(pszFilename, "/vsizip/") == nullptr)
795 486 : fp = VSICreateBufferedReaderHandle(fp);
796 :
797 1316 : CPLString osLayerName = CPLGetBasenameSafe(pszFilename);
798 1316 : CPLString osExt = CPLGetExtensionSafe(pszFilename);
799 658 : if (STARTS_WITH(pszFilename, "/vsigzip/") && EQUAL(osExt, "gz"))
800 : {
801 0 : if (strlen(pszFilename) > 7 &&
802 0 : EQUAL(pszFilename + strlen(pszFilename) - 7, ".csv.gz"))
803 : {
804 0 : osLayerName = osLayerName.substr(0, osLayerName.size() - 4);
805 0 : osExt = "csv";
806 : }
807 0 : else if (strlen(pszFilename) > 7 &&
808 0 : EQUAL(pszFilename + strlen(pszFilename) - 7, ".tsv.gz"))
809 : {
810 0 : osLayerName = osLayerName.substr(0, osLayerName.size() - 4);
811 0 : osExt = "tsv";
812 : }
813 0 : else if (strlen(pszFilename) > 7 &&
814 0 : EQUAL(pszFilename + strlen(pszFilename) - 7, ".psv.gz"))
815 : {
816 0 : osLayerName = osLayerName.substr(0, osLayerName.size() - 4);
817 0 : osExt = "psv";
818 : }
819 : }
820 :
821 658 : int nMaxLineSize = atoi(CPLGetConfigOption(
822 : "OGR_CSV_MAX_LINE_SIZE",
823 : CSLFetchNameValueDef(papszOpenOptionsIn, "MAX_LINE_SIZE",
824 658 : CPLSPrintf("%d", OGR_CSV_DEFAULT_MAX_LINE_SIZE))));
825 658 : size_t nMaxLineSizeAsSize_t = static_cast<size_t>(nMaxLineSize);
826 658 : if (nMaxLineSize == 0)
827 : {
828 0 : nMaxLineSize = -1;
829 0 : nMaxLineSizeAsSize_t = static_cast<size_t>(-1);
830 : }
831 :
832 : // Read and parse a line to detect separator.
833 :
834 1316 : std::string osLine;
835 : {
836 658 : const char *pszLine = CPLReadLine2L(fp, nMaxLineSize, nullptr);
837 658 : if (pszLine == nullptr)
838 : {
839 0 : VSIFCloseL(fp);
840 0 : return false;
841 : }
842 658 : osLine = pszLine;
843 : }
844 :
845 658 : char chDelimiter = ',';
846 : const char *pszDelimiter =
847 658 : CSLFetchNameValueDef(papszOpenOptionsIn, "SEPARATOR", "AUTO");
848 658 : if (EQUAL(pszDelimiter, "AUTO"))
849 : {
850 650 : chDelimiter = CSVDetectSeperator(osLine.c_str());
851 650 : if (chDelimiter != '\t' && osLine.find('\t') != std::string::npos)
852 : {
853 : // Force the delimiter to be TAB for a .tsv file that has a tabulation
854 : // in its first line */
855 0 : if (EQUAL(osExt, "tsv"))
856 : {
857 0 : chDelimiter = '\t';
858 : }
859 : else
860 : {
861 0 : for (int nDontHonourStrings = 0; nDontHonourStrings <= 1;
862 : nDontHonourStrings++)
863 : {
864 : const bool bHonourStrings =
865 0 : !CPL_TO_BOOL(nDontHonourStrings);
866 : // Read the first 2 lines to see if they have the same number
867 : // of fields, if using tabulation.
868 0 : VSIRewindL(fp);
869 0 : char **papszTokens = CSVReadParseLine3L(
870 : fp, nMaxLineSizeAsSize_t, "\t", bHonourStrings,
871 : false, // bKeepLeadingAndClosingQuotes
872 : false, // bMergeDelimiter
873 : true // bSkipBOM
874 : );
875 0 : const int nTokens1 = CSLCount(papszTokens);
876 0 : CSLDestroy(papszTokens);
877 0 : papszTokens = CSVReadParseLine3L(
878 : fp, nMaxLineSizeAsSize_t, "\t", bHonourStrings,
879 : false, // bKeepLeadingAndClosingQuotes
880 : false, // bMergeDelimiter
881 : true // bSkipBOM
882 : );
883 0 : const int nTokens2 = CSLCount(papszTokens);
884 0 : CSLDestroy(papszTokens);
885 0 : if (nTokens1 >= 2 && nTokens1 == nTokens2)
886 : {
887 0 : chDelimiter = '\t';
888 0 : break;
889 : }
890 : }
891 : }
892 : }
893 :
894 : // GNIS specific.
895 650 : if (pszGeonamesGeomFieldPrefix != nullptr &&
896 0 : osLine.find('|') != std::string::npos)
897 0 : chDelimiter = '|';
898 : }
899 8 : else if (EQUAL(pszDelimiter, "COMMA"))
900 4 : chDelimiter = ',';
901 4 : else if (EQUAL(pszDelimiter, "SEMICOLON"))
902 1 : chDelimiter = ';';
903 3 : else if (EQUAL(pszDelimiter, "TAB"))
904 1 : chDelimiter = '\t';
905 2 : else if (EQUAL(pszDelimiter, "SPACE"))
906 1 : chDelimiter = ' ';
907 1 : else if (EQUAL(pszDelimiter, "PIPE"))
908 1 : chDelimiter = '|';
909 : else
910 : {
911 0 : CPLError(CE_Warning, CPLE_AppDefined,
912 : "SEPARATOR=%s not understood, use one of COMMA, "
913 : "SEMICOLON, TAB, SPACE or PIPE.",
914 : pszDelimiter);
915 : }
916 :
917 658 : VSIRewindL(fp);
918 :
919 : // Create a layer.
920 658 : if (pszNfdcRunwaysGeomField != nullptr)
921 : {
922 0 : osLayerName += "_";
923 0 : osLayerName += pszNfdcRunwaysGeomField;
924 : }
925 658 : else if (pszGeonamesGeomFieldPrefix != nullptr &&
926 0 : !EQUAL(pszGeonamesGeomFieldPrefix, ""))
927 : {
928 0 : osLayerName += "_";
929 0 : osLayerName += pszGeonamesGeomFieldPrefix;
930 : }
931 658 : if (EQUAL(pszFilename, "/vsistdin/"))
932 0 : osLayerName = "layer";
933 :
934 : auto poCSVLayer =
935 : std::make_unique<OGRCSVLayer>(this, osLayerName, fp, nMaxLineSize,
936 1316 : pszFilename, FALSE, bUpdate, chDelimiter);
937 658 : poCSVLayer->BuildFeatureDefn(pszNfdcRunwaysGeomField,
938 : pszGeonamesGeomFieldPrefix,
939 : papszOpenOptionsIn);
940 658 : if (bUpdate)
941 : {
942 88 : m_apoLayers.emplace_back(std::make_unique<OGRCSVEditableLayer>(
943 176 : poCSVLayer.release(), papszOpenOptionsIn));
944 : }
945 : else
946 : {
947 570 : m_apoLayers.emplace_back(std::move(poCSVLayer));
948 :
949 570 : if (!DealWithOgrSchemaOpenOption(papszOpenOptionsIn))
950 : {
951 1 : m_apoLayers.pop_back();
952 1 : return false;
953 : }
954 : }
955 :
956 657 : return true;
957 : }
958 :
959 : /************************************************************************/
960 : /* ICreateLayer() */
961 : /************************************************************************/
962 :
963 : OGRLayer *
964 150 : OGRCSVDataSource::ICreateLayer(const char *pszLayerName,
965 : const OGRGeomFieldDefn *poSrcGeomFieldDefn,
966 : CSLConstList papszOptions)
967 : {
968 : // Verify we are in update mode.
969 150 : if (!bUpdate)
970 : {
971 1 : CPLError(CE_Failure, CPLE_NoWriteAccess,
972 : "Data source %s opened read-only.\n"
973 : "New layer %s cannot be created.",
974 : pszName, pszLayerName);
975 :
976 1 : return nullptr;
977 : }
978 :
979 : const auto eGType =
980 149 : poSrcGeomFieldDefn ? poSrcGeomFieldDefn->GetType() : wkbNone;
981 : const auto poSpatialRef =
982 149 : poSrcGeomFieldDefn ? poSrcGeomFieldDefn->GetSpatialRef() : nullptr;
983 :
984 : // Verify that the datasource is a directory.
985 : VSIStatBufL sStatBuf;
986 :
987 149 : if (STARTS_WITH(pszName, "/vsizip/"))
988 : {
989 : // Do nothing.
990 : }
991 297 : else if (!EQUAL(pszName, "/vsistdout/") &&
992 148 : (VSIStatL(pszName, &sStatBuf) != 0 ||
993 147 : !VSI_ISDIR(sStatBuf.st_mode)))
994 : {
995 1 : CPLError(CE_Failure, CPLE_AppDefined,
996 : "Attempt to create csv layer (file) against a "
997 : "non-directory datasource.");
998 1 : return nullptr;
999 : }
1000 :
1001 : const bool bCreateCSVT =
1002 148 : CPLTestBool(CSLFetchNameValueDef(papszOptions, "CREATE_CSVT", "NO"));
1003 :
1004 : // What filename would we use?
1005 296 : CPLString osFilename;
1006 :
1007 148 : if (strcmp(pszName, "/vsistdout/") == 0)
1008 : {
1009 1 : osFilename = pszName;
1010 1 : if (bCreateCSVT)
1011 : {
1012 0 : CPLError(CE_Failure, CPLE_AppDefined,
1013 : "CREATE_CSVT is not compatible with /vsistdout/ output");
1014 0 : return nullptr;
1015 : }
1016 : }
1017 147 : else if (osDefaultCSVName != "")
1018 : {
1019 77 : osFilename = CPLFormFilenameSafe(pszName, osDefaultCSVName, nullptr);
1020 77 : osDefaultCSVName = "";
1021 : }
1022 : else
1023 : {
1024 70 : if (CPLLaunderForFilenameSafe(pszLayerName, nullptr) != pszLayerName)
1025 : {
1026 1 : CPLError(CE_Failure, CPLE_AppDefined,
1027 : "Illegal characters in '%s' to form a valid filename",
1028 : pszLayerName);
1029 1 : return nullptr;
1030 : }
1031 69 : osFilename = CPLFormFilenameSafe(pszName, pszLayerName, "csv");
1032 : }
1033 :
1034 : // Does this directory/file already exist?
1035 147 : if (VSIStatL(osFilename, &sStatBuf) == 0)
1036 : {
1037 1 : CPLError(CE_Failure, CPLE_AppDefined,
1038 : "Attempt to create layer %s, but %s already exists.",
1039 : pszLayerName, osFilename.c_str());
1040 1 : return nullptr;
1041 : }
1042 :
1043 : // Create the empty file.
1044 :
1045 146 : const char *pszDelimiter = CSLFetchNameValue(papszOptions, "SEPARATOR");
1046 146 : char chDelimiter = ',';
1047 146 : if (pszDelimiter != nullptr)
1048 : {
1049 2 : if (EQUAL(pszDelimiter, "COMMA"))
1050 0 : chDelimiter = ',';
1051 2 : else if (EQUAL(pszDelimiter, "SEMICOLON"))
1052 1 : chDelimiter = ';';
1053 1 : else if (EQUAL(pszDelimiter, "TAB"))
1054 0 : chDelimiter = '\t';
1055 1 : else if (EQUAL(pszDelimiter, "SPACE"))
1056 1 : chDelimiter = ' ';
1057 0 : else if (EQUAL(pszDelimiter, "PIPE"))
1058 0 : chDelimiter = '|';
1059 : else
1060 : {
1061 0 : CPLError(CE_Warning, CPLE_AppDefined,
1062 : "SEPARATOR=%s not understood, use one of COMMA, "
1063 : "SEMICOLON, TAB, SPACE or PIPE.",
1064 : pszDelimiter);
1065 : }
1066 : }
1067 :
1068 : // Create a layer.
1069 :
1070 : auto poCSVLayer = std::make_unique<OGRCSVLayer>(
1071 292 : this, pszLayerName, nullptr, -1, osFilename, true, true, chDelimiter);
1072 :
1073 146 : poCSVLayer->BuildFeatureDefn();
1074 :
1075 : // Was a particular CRLF order requested?
1076 146 : const char *pszCRLFFormat = CSLFetchNameValue(papszOptions, "LINEFORMAT");
1077 146 : bool bUseCRLF = false;
1078 :
1079 146 : if (pszCRLFFormat == nullptr)
1080 : {
1081 : #ifdef _WIN32
1082 : bUseCRLF = true;
1083 : #endif
1084 : }
1085 18 : else if (EQUAL(pszCRLFFormat, "CRLF"))
1086 : {
1087 1 : bUseCRLF = true;
1088 : }
1089 17 : else if (!EQUAL(pszCRLFFormat, "LF"))
1090 : {
1091 0 : CPLError(CE_Warning, CPLE_AppDefined,
1092 : "LINEFORMAT=%s not understood, use one of CRLF or LF.",
1093 : pszCRLFFormat);
1094 : #ifdef _WIN32
1095 : bUseCRLF = true;
1096 : #endif
1097 : }
1098 :
1099 146 : poCSVLayer->SetCRLF(bUseCRLF);
1100 :
1101 : const char *pszStringQuoting =
1102 146 : CSLFetchNameValueDef(papszOptions, "STRING_QUOTING", "IF_AMBIGUOUS");
1103 292 : poCSVLayer->SetStringQuoting(
1104 146 : EQUAL(pszStringQuoting, "IF_NEEDED")
1105 : ? OGRCSVLayer::StringQuoting::IF_NEEDED
1106 133 : : EQUAL(pszStringQuoting, "ALWAYS")
1107 133 : ? OGRCSVLayer::StringQuoting::ALWAYS
1108 : : OGRCSVLayer::StringQuoting::IF_AMBIGUOUS);
1109 :
1110 : // Should we write the geometry?
1111 146 : const char *pszGeometry = CSLFetchNameValue(papszOptions, "GEOMETRY");
1112 146 : if (bEnableGeometryFields)
1113 : {
1114 25 : poCSVLayer->SetWriteGeometry(
1115 : eGType, OGR_CSV_GEOM_AS_WKT,
1116 : CSLFetchNameValueDef(papszOptions, "GEOMETRY_NAME", "WKT"));
1117 : }
1118 121 : else if (pszGeometry != nullptr)
1119 : {
1120 27 : if (EQUAL(pszGeometry, "AS_WKT"))
1121 : {
1122 17 : poCSVLayer->SetWriteGeometry(
1123 : eGType, OGR_CSV_GEOM_AS_WKT,
1124 : CSLFetchNameValueDef(papszOptions, "GEOMETRY_NAME", "WKT"));
1125 : }
1126 10 : else if (EQUAL(pszGeometry, "AS_XYZ") || EQUAL(pszGeometry, "AS_XY") ||
1127 5 : EQUAL(pszGeometry, "AS_YX"))
1128 : {
1129 6 : if (eGType == wkbUnknown || wkbFlatten(eGType) == wkbPoint)
1130 : {
1131 10 : poCSVLayer->SetWriteGeometry(
1132 5 : eGType, EQUAL(pszGeometry, "AS_XYZ") ? OGR_CSV_GEOM_AS_XYZ
1133 3 : : EQUAL(pszGeometry, "AS_XY") ? OGR_CSV_GEOM_AS_XY
1134 : : OGR_CSV_GEOM_AS_YX);
1135 : }
1136 : else
1137 : {
1138 1 : CPLError(CE_Failure, CPLE_AppDefined,
1139 : "Geometry type %s is not compatible with "
1140 : "GEOMETRY=%s.",
1141 : OGRGeometryTypeToName(eGType), pszGeometry);
1142 1 : return nullptr;
1143 : }
1144 : }
1145 4 : else if (!EQUAL(pszGeometry, "NONE"))
1146 : {
1147 1 : CPLError(CE_Failure, CPLE_AppDefined,
1148 : "Unsupported value %s for creation option GEOMETRY",
1149 : pszGeometry);
1150 1 : return nullptr;
1151 : }
1152 : }
1153 94 : else if (eGType != wkbUnknown && eGType != wkbNone)
1154 : {
1155 42 : CPLError(CE_Warning, CPLE_AppDefined,
1156 : "Requested to create spatial CSV layer but GEOMETRY layer "
1157 : "creation option not set. No geometry will be output.");
1158 : }
1159 :
1160 : // Should we create a CSVT file?
1161 144 : if (bCreateCSVT)
1162 : {
1163 29 : poCSVLayer->SetCreateCSVT(true);
1164 :
1165 : // Create .prj file.
1166 29 : if (poSpatialRef != nullptr)
1167 : {
1168 8 : char *pszWKT = nullptr;
1169 8 : poSpatialRef->exportToWkt(&pszWKT);
1170 8 : if (pszWKT)
1171 : {
1172 8 : VSILFILE *fpPRJ = VSIFOpenL(
1173 16 : CPLResetExtensionSafe(osFilename, "prj").c_str(), "wb");
1174 8 : if (fpPRJ)
1175 : {
1176 8 : CPL_IGNORE_RET_VAL(VSIFPrintfL(fpPRJ, "%s\n", pszWKT));
1177 8 : VSIFCloseL(fpPRJ);
1178 : }
1179 8 : CPLFree(pszWKT);
1180 : }
1181 : }
1182 : }
1183 :
1184 : // Should we write a UTF8 BOM?
1185 144 : const char *pszWriteBOM = CSLFetchNameValue(papszOptions, "WRITE_BOM");
1186 144 : if (pszWriteBOM)
1187 2 : poCSVLayer->SetWriteBOM(CPLTestBool(pszWriteBOM));
1188 :
1189 144 : auto poFeatureDefn = poCSVLayer->GetLayerDefn();
1190 144 : if (poFeatureDefn->GetGeomFieldCount() > 0 && poSrcGeomFieldDefn)
1191 : {
1192 39 : auto poGeomFieldDefn = poFeatureDefn->GetGeomFieldDefn(0);
1193 39 : poGeomFieldDefn->SetCoordinatePrecision(
1194 : poSrcGeomFieldDefn->GetCoordinatePrecision());
1195 : }
1196 :
1197 144 : poCSVLayer->SetWriteHeader(CPLTestBool(CSLFetchNameValueDef(
1198 : papszOptions, "HEADER",
1199 : CSLFetchNameValueDef(papszOptions, "HEADERS", "YES"))));
1200 :
1201 144 : if (osFilename != "/vsistdout/")
1202 143 : m_apoLayers.emplace_back(std::make_unique<OGRCSVEditableLayer>(
1203 286 : poCSVLayer.release(), nullptr));
1204 : else
1205 1 : m_apoLayers.emplace_back(std::move(poCSVLayer));
1206 :
1207 144 : return m_apoLayers.back()->GetLayer();
1208 : }
1209 :
1210 : /************************************************************************/
1211 : /* DeleteLayer() */
1212 : /************************************************************************/
1213 :
1214 20 : OGRErr OGRCSVDataSource::DeleteLayer(int iLayer)
1215 :
1216 : {
1217 : // Verify we are in update mode.
1218 20 : if (!bUpdate)
1219 : {
1220 1 : CPLError(CE_Failure, CPLE_NoWriteAccess,
1221 : "Data source %s opened read-only.\n"
1222 : "Layer %d cannot be deleted.",
1223 : pszName, iLayer);
1224 :
1225 1 : return OGRERR_FAILURE;
1226 : }
1227 :
1228 19 : if (iLayer < 0 || iLayer >= GetLayerCount())
1229 : {
1230 2 : CPLError(CE_Failure, CPLE_AppDefined,
1231 : "Layer %d not in legal range of 0 to %d.", iLayer,
1232 2 : GetLayerCount() - 1);
1233 2 : return OGRERR_FAILURE;
1234 : }
1235 :
1236 34 : for (const auto &osFilename : m_apoLayers[iLayer]->GetFileList())
1237 : {
1238 17 : VSIUnlink(osFilename.c_str());
1239 : }
1240 :
1241 17 : m_apoLayers.erase(m_apoLayers.begin() + iLayer);
1242 :
1243 17 : return OGRERR_NONE;
1244 : }
1245 :
1246 : /************************************************************************/
1247 : /* CreateForSingleFile() */
1248 : /************************************************************************/
1249 :
1250 78 : void OGRCSVDataSource::CreateForSingleFile(const char *pszDirname,
1251 : const char *pszFilename)
1252 : {
1253 78 : pszName = CPLStrdup(pszDirname);
1254 78 : bUpdate = true;
1255 78 : osDefaultCSVName = CPLGetFilename(pszFilename);
1256 78 : }
1257 :
1258 : /************************************************************************/
1259 : /* GetFileList() */
1260 : /************************************************************************/
1261 :
1262 7 : char **OGRCSVDataSource::GetFileList()
1263 : {
1264 14 : CPLStringList oFileList;
1265 19 : for (auto &poLayer : m_apoLayers)
1266 : {
1267 35 : for (const auto &osFilename : poLayer->GetFileList())
1268 : {
1269 23 : oFileList.AddString(osFilename.c_str());
1270 : }
1271 : }
1272 14 : return oFileList.StealList();
1273 : }
|