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 227 : OGRCSVEditableLayerSynchronizer(OGRCSVLayer *poCSVLayer,
50 : CSLConstList papszOpenOptions)
51 227 : : m_poCSVLayer(poCSVLayer),
52 227 : m_papszOpenOptions(CSLDuplicate(papszOpenOptions))
53 : {
54 227 : }
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 454 : OGRCSVEditableLayerSynchronizer::~OGRCSVEditableLayerSynchronizer()
72 : {
73 227 : CSLDestroy(m_papszOpenOptions);
74 454 : }
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 356 : OGRLayer *GetLayer() override
311 : {
312 356 : 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 227 : OGRCSVEditableLayer::OGRCSVEditableLayer(OGRCSVLayer *poCSVLayer,
335 227 : CSLConstList papszOpenOptions)
336 : : OGREditableLayer(
337 : poCSVLayer, true,
338 227 : new OGRCSVEditableLayerSynchronizer(poCSVLayer, papszOpenOptions),
339 454 : true)
340 : {
341 227 : SetSupportsCreateGeomField(true);
342 227 : SetSupportsCurveGeometries(true);
343 227 : }
344 :
345 : /************************************************************************/
346 : /* CreateField() */
347 : /************************************************************************/
348 :
349 482 : OGRErr OGRCSVEditableLayer::CreateField(const OGRFieldDefn *poNewField,
350 : int bApproxOK)
351 :
352 : {
353 482 : 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 482 : if (m_oSetFields.empty())
360 : {
361 120 : 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 964 : const OGRCSVCreateFieldAction eAction = OGRCSVLayer::PreCreateField(
371 482 : m_poEditableFeatureDefn, m_oSetFields, poNewField, bApproxOK);
372 482 : if (eAction == CREATE_FIELD_DO_NOTHING)
373 0 : return OGRERR_NONE;
374 482 : if (eAction == CREATE_FIELD_ERROR)
375 1 : return OGRERR_FAILURE;
376 481 : OGRErr eErr = OGREditableLayer::CreateField(poNewField, bApproxOK);
377 481 : if (eErr == OGRERR_NONE)
378 : {
379 481 : m_oSetFields.insert(CPLString(poNewField->GetNameRef()).toupper());
380 : }
381 481 : 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 2758 : OGRCSVDataSource::~OGRCSVDataSource()
427 :
428 : {
429 1379 : m_apoLayers.clear();
430 :
431 1379 : if (bUpdate)
432 267 : OGRCSVDriverRemoveFromMap(pszName, this);
433 :
434 1379 : CPLFree(pszName);
435 2758 : }
436 :
437 : /************************************************************************/
438 : /* TestCapability() */
439 : /************************************************************************/
440 :
441 218 : int OGRCSVDataSource::TestCapability(const char *pszCap) const
442 :
443 : {
444 218 : if (EQUAL(pszCap, ODsCCreateLayer))
445 71 : return bUpdate;
446 147 : else if (EQUAL(pszCap, ODsCDeleteLayer))
447 19 : return bUpdate;
448 128 : else if (EQUAL(pszCap, ODsCCreateGeomFieldAfterCreateLayer))
449 36 : return bUpdate && bEnableGeometryFields;
450 92 : else if (EQUAL(pszCap, ODsCCurveGeometries))
451 3 : return TRUE;
452 89 : else if (EQUAL(pszCap, ODsCMeasuredGeometries))
453 3 : return TRUE;
454 86 : else if (EQUAL(pszCap, ODsCZGeometries))
455 2 : return TRUE;
456 84 : else if (EQUAL(pszCap, ODsCRandomLayerWrite))
457 0 : return bUpdate;
458 : else
459 84 : return FALSE;
460 : }
461 :
462 : /************************************************************************/
463 : /* GetLayer() */
464 : /************************************************************************/
465 :
466 978 : const OGRLayer *OGRCSVDataSource::GetLayer(int iLayer) const
467 :
468 : {
469 978 : if (iLayer < 0 || iLayer >= static_cast<int>(m_apoLayers.size()))
470 2 : return nullptr;
471 :
472 976 : return m_apoLayers[iLayer]->GetLayer();
473 : }
474 :
475 : /************************************************************************/
476 : /* GetRealExtension() */
477 : /************************************************************************/
478 :
479 8398 : CPLString OGRCSVDataSource::GetRealExtension(CPLString osFilename)
480 : {
481 16796 : CPLString osExt = CPLGetExtensionSafe(osFilename);
482 8398 : 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 8398 : return osExt;
495 : }
496 :
497 : /************************************************************************/
498 : /* Open() */
499 : /************************************************************************/
500 :
501 1303 : bool OGRCSVDataSource::Open(const char *pszFilename, bool bUpdateIn,
502 : bool bForceOpen, CSLConstList papszOpenOptionsIn,
503 : bool bSingleDriver)
504 :
505 : {
506 1303 : pszName = CPLStrdup(pszFilename);
507 1303 : bUpdate = CPL_TO_BOOL(bUpdateIn);
508 :
509 1303 : if (bUpdate && bForceOpen && EQUAL(pszFilename, "/vsistdout/"))
510 1 : return TRUE;
511 :
512 : // For writable /vsizip/, do nothing more.
513 1302 : if (bUpdate && bForceOpen && STARTS_WITH(pszFilename, "/vsizip/"))
514 0 : return TRUE;
515 :
516 2604 : CPLString osFilename(pszFilename);
517 2604 : const CPLString osBaseFilename = CPLGetFilename(pszFilename);
518 2604 : const CPLString osExt = GetRealExtension(osFilename);
519 :
520 1302 : bool bUSGeonamesFile = false;
521 1302 : 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 1302 : if (EQUAL(osBaseFilename, "NfdcFacilities.xls") ||
530 1302 : EQUAL(osBaseFilename, "NfdcRunways.xls") ||
531 3906 : EQUAL(osBaseFilename, "NfdcRemarks.xls") ||
532 1302 : EQUAL(osBaseFilename, "NfdcSchedules.xls"))
533 : {
534 0 : if (bUpdate)
535 0 : return FALSE;
536 0 : bSingleDriver = true;
537 : }
538 1302 : else if ((STARTS_WITH_CI(osBaseFilename, "NationalFile_") ||
539 1302 : STARTS_WITH_CI(osBaseFilename, "POP_PLACES_") ||
540 1302 : STARTS_WITH_CI(osBaseFilename, "HIST_FEATURES_") ||
541 1302 : STARTS_WITH_CI(osBaseFilename, "US_CONCISE_") ||
542 1302 : STARTS_WITH_CI(osBaseFilename, "AllNames_") ||
543 1302 : STARTS_WITH_CI(osBaseFilename, "Feature_Description_History_") ||
544 1302 : STARTS_WITH_CI(osBaseFilename, "ANTARCTICA_") ||
545 1302 : STARTS_WITH_CI(osBaseFilename, "GOVT_UNITS_") ||
546 1302 : STARTS_WITH_CI(osBaseFilename, "NationalFedCodes_") ||
547 1302 : STARTS_WITH_CI(osBaseFilename, "AllStates_") ||
548 2604 : STARTS_WITH_CI(osBaseFilename, "AllStatesFedCodes_") ||
549 1302 : (osBaseFilename.size() > 2 &&
550 2581 : STARTS_WITH_CI(osBaseFilename + 2, "_Features_")) ||
551 1302 : (osBaseFilename.size() > 2 &&
552 2604 : 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 2603 : else if (EQUAL(osBaseFilename, "allCountries.txt") ||
566 1301 : 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 1302 : if (VSIStatExL(osFilename, &sStatBuf, VSI_STAT_NATURE_FLAG) != 0)
582 0 : return FALSE;
583 :
584 : // Is this a single CSV file?
585 1720 : 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 797 : 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 791 : if (!VSI_ISDIR(sStatBuf.st_mode))
647 0 : return FALSE;
648 :
649 : // Scan through for entries ending in .csv.
650 791 : int nNotCSVCount = 0;
651 791 : const CPLStringList aosFilenames(VSIReadDir(osFilename));
652 :
653 26904 : for (int i = 0; i < aosFilenames.size(); i++)
654 : {
655 26113 : if (EQUAL(aosFilenames[i], ".") || EQUAL(aosFilenames[i], ".."))
656 25970 : continue;
657 :
658 25339 : const std::string osThisExt = CPLGetExtensionSafe(aosFilenames[i]);
659 25339 : if (EQUAL(osThisExt.c_str(), "csvt") || EQUAL(osThisExt.c_str(), "prj"))
660 94 : continue;
661 :
662 : const CPLString oSubFilename =
663 25245 : CPLFormFilenameSafe(osFilename, aosFilenames[i], nullptr);
664 50490 : if (VSIStatL(oSubFilename, &sStatBuf) != 0 ||
665 25245 : !VSI_ISREG(sStatBuf.st_mode))
666 : {
667 167 : nNotCSVCount++;
668 167 : continue;
669 : }
670 :
671 25078 : if (EQUAL(osThisExt.c_str(), "csv"))
672 : {
673 143 : 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 793 : return bForceOpen || nNotCSVCount < GetLayerCount() ||
719 793 : (bSingleDriver && GetLayerCount() > 0);
720 : }
721 :
722 215367 : const std::vector<int> &OGRCSVDataSource::DeletedFieldIndexes() const
723 : {
724 215367 : return m_oDeletedFieldIndexes;
725 : }
726 :
727 : /************************************************************************/
728 : /* DealWithOgrSchemaOpenOption() */
729 : /************************************************************************/
730 565 : bool OGRCSVDataSource::DealWithOgrSchemaOpenOption(
731 : CSLConstList papszOpenOptionsIn)
732 : {
733 : const std::string osFieldsSchemaOverrideParam =
734 1130 : CSLFetchNameValueDef(papszOpenOptionsIn, "OGR_SCHEMA", "");
735 :
736 565 : 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 564 : return true;
767 : }
768 :
769 : /************************************************************************/
770 : /* OpenTable() */
771 : /************************************************************************/
772 :
773 653 : bool OGRCSVDataSource::OpenTable(const char *pszFilename,
774 : CSLConstList papszOpenOptionsIn,
775 : const char *pszNfdcRunwaysGeomField,
776 : const char *pszGeonamesGeomFieldPrefix)
777 :
778 : {
779 : // Open the file.
780 653 : VSILFILE *fp = nullptr;
781 :
782 653 : if (bUpdate)
783 88 : fp = VSIFOpenExL(pszFilename, "rb+", true);
784 : else
785 565 : fp = VSIFOpenExL(pszFilename, "rb", true);
786 653 : if (fp == nullptr)
787 : {
788 0 : CPLError(CE_Warning, CPLE_OpenFailed, "Failed to open %s.",
789 : VSIGetLastErrorMsg());
790 0 : return false;
791 : }
792 :
793 653 : if (!bUpdate && strstr(pszFilename, "/vsigzip/") == nullptr &&
794 565 : strstr(pszFilename, "/vsizip/") == nullptr)
795 481 : fp = VSICreateBufferedReaderHandle(fp);
796 :
797 1306 : CPLString osLayerName = CPLGetBasenameSafe(pszFilename);
798 1306 : CPLString osExt = CPLGetExtensionSafe(pszFilename);
799 653 : 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 653 : int nMaxLineSize = atoi(CPLGetConfigOption(
822 : "OGR_CSV_MAX_LINE_SIZE",
823 : CSLFetchNameValueDef(papszOpenOptionsIn, "MAX_LINE_SIZE",
824 653 : CPLSPrintf("%d", OGR_CSV_DEFAULT_MAX_LINE_SIZE))));
825 653 : size_t nMaxLineSizeAsSize_t = static_cast<size_t>(nMaxLineSize);
826 653 : 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 1306 : std::string osLine;
835 : {
836 653 : const char *pszLine = CPLReadLine2L(fp, nMaxLineSize, nullptr);
837 653 : if (pszLine == nullptr)
838 : {
839 0 : VSIFCloseL(fp);
840 0 : return false;
841 : }
842 653 : osLine = pszLine;
843 : }
844 :
845 653 : char chDelimiter = ',';
846 : const char *pszDelimiter =
847 653 : CSLFetchNameValueDef(papszOpenOptionsIn, "SEPARATOR", "AUTO");
848 653 : if (EQUAL(pszDelimiter, "AUTO"))
849 : {
850 645 : chDelimiter = CSVDetectSeperator(osLine.c_str());
851 645 : 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 645 : 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 653 : VSIRewindL(fp);
918 :
919 : // Create a layer.
920 653 : if (pszNfdcRunwaysGeomField != nullptr)
921 : {
922 0 : osLayerName += "_";
923 0 : osLayerName += pszNfdcRunwaysGeomField;
924 : }
925 653 : else if (pszGeonamesGeomFieldPrefix != nullptr &&
926 0 : !EQUAL(pszGeonamesGeomFieldPrefix, ""))
927 : {
928 0 : osLayerName += "_";
929 0 : osLayerName += pszGeonamesGeomFieldPrefix;
930 : }
931 653 : if (EQUAL(pszFilename, "/vsistdin/"))
932 0 : osLayerName = "layer";
933 :
934 : auto poCSVLayer =
935 : std::make_unique<OGRCSVLayer>(this, osLayerName, fp, nMaxLineSize,
936 1306 : pszFilename, FALSE, bUpdate, chDelimiter);
937 653 : poCSVLayer->BuildFeatureDefn(pszNfdcRunwaysGeomField,
938 : pszGeonamesGeomFieldPrefix,
939 : papszOpenOptionsIn);
940 653 : if (bUpdate)
941 : {
942 88 : m_apoLayers.emplace_back(std::make_unique<OGRCSVEditableLayer>(
943 176 : poCSVLayer.release(), papszOpenOptionsIn));
944 : }
945 : else
946 : {
947 565 : m_apoLayers.emplace_back(std::move(poCSVLayer));
948 :
949 565 : if (!DealWithOgrSchemaOpenOption(papszOpenOptionsIn))
950 : {
951 1 : m_apoLayers.pop_back();
952 1 : return false;
953 : }
954 : }
955 :
956 652 : return true;
957 : }
958 :
959 : /************************************************************************/
960 : /* ICreateLayer() */
961 : /************************************************************************/
962 :
963 : OGRLayer *
964 146 : OGRCSVDataSource::ICreateLayer(const char *pszLayerName,
965 : const OGRGeomFieldDefn *poSrcGeomFieldDefn,
966 : CSLConstList papszOptions)
967 : {
968 : // Verify we are in update mode.
969 146 : 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 145 : poSrcGeomFieldDefn ? poSrcGeomFieldDefn->GetType() : wkbNone;
981 : const auto poSpatialRef =
982 145 : poSrcGeomFieldDefn ? poSrcGeomFieldDefn->GetSpatialRef() : nullptr;
983 :
984 : // Verify that the datasource is a directory.
985 : VSIStatBufL sStatBuf;
986 :
987 145 : if (STARTS_WITH(pszName, "/vsizip/"))
988 : {
989 : // Do nothing.
990 : }
991 289 : else if (!EQUAL(pszName, "/vsistdout/") &&
992 144 : (VSIStatL(pszName, &sStatBuf) != 0 ||
993 143 : !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 144 : CPLTestBool(CSLFetchNameValueDef(papszOptions, "CREATE_CSVT", "NO"));
1003 :
1004 : // What filename would we use?
1005 288 : CPLString osFilename;
1006 :
1007 144 : 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 143 : else if (osDefaultCSVName != "")
1018 : {
1019 76 : osFilename = CPLFormFilenameSafe(pszName, osDefaultCSVName, nullptr);
1020 76 : osDefaultCSVName = "";
1021 : }
1022 : else
1023 : {
1024 67 : 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 66 : osFilename = CPLFormFilenameSafe(pszName, pszLayerName, "csv");
1032 : }
1033 :
1034 : // Does this directory/file already exist?
1035 143 : 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 142 : const char *pszDelimiter = CSLFetchNameValue(papszOptions, "SEPARATOR");
1046 142 : char chDelimiter = ',';
1047 142 : 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 284 : this, pszLayerName, nullptr, -1, osFilename, true, true, chDelimiter);
1072 :
1073 142 : poCSVLayer->BuildFeatureDefn();
1074 :
1075 : // Was a particular CRLF order requested?
1076 142 : const char *pszCRLFFormat = CSLFetchNameValue(papszOptions, "LINEFORMAT");
1077 142 : bool bUseCRLF = false;
1078 :
1079 142 : 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 142 : poCSVLayer->SetCRLF(bUseCRLF);
1100 :
1101 : const char *pszStringQuoting =
1102 142 : CSLFetchNameValueDef(papszOptions, "STRING_QUOTING", "IF_AMBIGUOUS");
1103 284 : poCSVLayer->SetStringQuoting(
1104 142 : EQUAL(pszStringQuoting, "IF_NEEDED")
1105 : ? OGRCSVLayer::StringQuoting::IF_NEEDED
1106 129 : : EQUAL(pszStringQuoting, "ALWAYS")
1107 129 : ? OGRCSVLayer::StringQuoting::ALWAYS
1108 : : OGRCSVLayer::StringQuoting::IF_AMBIGUOUS);
1109 :
1110 : // Should we write the geometry?
1111 142 : const char *pszGeometry = CSLFetchNameValue(papszOptions, "GEOMETRY");
1112 142 : if (bEnableGeometryFields)
1113 : {
1114 11 : poCSVLayer->SetWriteGeometry(
1115 : eGType, OGR_CSV_GEOM_AS_WKT,
1116 : CSLFetchNameValueDef(papszOptions, "GEOMETRY_NAME", "WKT"));
1117 : }
1118 131 : else if (pszGeometry != nullptr)
1119 : {
1120 35 : if (EQUAL(pszGeometry, "AS_WKT"))
1121 : {
1122 28 : poCSVLayer->SetWriteGeometry(
1123 : eGType, OGR_CSV_GEOM_AS_WKT,
1124 : CSLFetchNameValueDef(papszOptions, "GEOMETRY_NAME", "WKT"));
1125 : }
1126 7 : else if (EQUAL(pszGeometry, "AS_XYZ") || EQUAL(pszGeometry, "AS_XY") ||
1127 2 : 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 : else
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 :
1154 : // Should we create a CSVT file?
1155 140 : if (bCreateCSVT)
1156 : {
1157 29 : poCSVLayer->SetCreateCSVT(true);
1158 :
1159 : // Create .prj file.
1160 29 : if (poSpatialRef != nullptr)
1161 : {
1162 8 : char *pszWKT = nullptr;
1163 8 : poSpatialRef->exportToWkt(&pszWKT);
1164 8 : if (pszWKT)
1165 : {
1166 8 : VSILFILE *fpPRJ = VSIFOpenL(
1167 16 : CPLResetExtensionSafe(osFilename, "prj").c_str(), "wb");
1168 8 : if (fpPRJ)
1169 : {
1170 8 : CPL_IGNORE_RET_VAL(VSIFPrintfL(fpPRJ, "%s\n", pszWKT));
1171 8 : VSIFCloseL(fpPRJ);
1172 : }
1173 8 : CPLFree(pszWKT);
1174 : }
1175 : }
1176 : }
1177 :
1178 : // Should we write a UTF8 BOM?
1179 140 : const char *pszWriteBOM = CSLFetchNameValue(papszOptions, "WRITE_BOM");
1180 140 : if (pszWriteBOM)
1181 2 : poCSVLayer->SetWriteBOM(CPLTestBool(pszWriteBOM));
1182 :
1183 140 : auto poFeatureDefn = poCSVLayer->GetLayerDefn();
1184 140 : if (poFeatureDefn->GetGeomFieldCount() > 0 && poSrcGeomFieldDefn)
1185 : {
1186 39 : auto poGeomFieldDefn = poFeatureDefn->GetGeomFieldDefn(0);
1187 39 : poGeomFieldDefn->SetCoordinatePrecision(
1188 : poSrcGeomFieldDefn->GetCoordinatePrecision());
1189 : }
1190 :
1191 140 : poCSVLayer->SetWriteHeader(CPLTestBool(CSLFetchNameValueDef(
1192 : papszOptions, "HEADER",
1193 : CSLFetchNameValueDef(papszOptions, "HEADERS", "YES"))));
1194 :
1195 140 : if (osFilename != "/vsistdout/")
1196 139 : m_apoLayers.emplace_back(std::make_unique<OGRCSVEditableLayer>(
1197 278 : poCSVLayer.release(), nullptr));
1198 : else
1199 1 : m_apoLayers.emplace_back(std::move(poCSVLayer));
1200 :
1201 140 : return m_apoLayers.back()->GetLayer();
1202 : }
1203 :
1204 : /************************************************************************/
1205 : /* DeleteLayer() */
1206 : /************************************************************************/
1207 :
1208 20 : OGRErr OGRCSVDataSource::DeleteLayer(int iLayer)
1209 :
1210 : {
1211 : // Verify we are in update mode.
1212 20 : if (!bUpdate)
1213 : {
1214 1 : CPLError(CE_Failure, CPLE_NoWriteAccess,
1215 : "Data source %s opened read-only.\n"
1216 : "Layer %d cannot be deleted.",
1217 : pszName, iLayer);
1218 :
1219 1 : return OGRERR_FAILURE;
1220 : }
1221 :
1222 19 : if (iLayer < 0 || iLayer >= GetLayerCount())
1223 : {
1224 2 : CPLError(CE_Failure, CPLE_AppDefined,
1225 : "Layer %d not in legal range of 0 to %d.", iLayer,
1226 2 : GetLayerCount() - 1);
1227 2 : return OGRERR_FAILURE;
1228 : }
1229 :
1230 34 : for (const auto &osFilename : m_apoLayers[iLayer]->GetFileList())
1231 : {
1232 17 : VSIUnlink(osFilename.c_str());
1233 : }
1234 :
1235 17 : m_apoLayers.erase(m_apoLayers.begin() + iLayer);
1236 :
1237 17 : return OGRERR_NONE;
1238 : }
1239 :
1240 : /************************************************************************/
1241 : /* CreateForSingleFile() */
1242 : /************************************************************************/
1243 :
1244 77 : void OGRCSVDataSource::CreateForSingleFile(const char *pszDirname,
1245 : const char *pszFilename)
1246 : {
1247 77 : pszName = CPLStrdup(pszDirname);
1248 77 : bUpdate = true;
1249 77 : osDefaultCSVName = CPLGetFilename(pszFilename);
1250 77 : }
1251 :
1252 : /************************************************************************/
1253 : /* GetFileList() */
1254 : /************************************************************************/
1255 :
1256 7 : char **OGRCSVDataSource::GetFileList()
1257 : {
1258 14 : CPLStringList oFileList;
1259 19 : for (auto &poLayer : m_apoLayers)
1260 : {
1261 35 : for (const auto &osFilename : poLayer->GetFileList())
1262 : {
1263 23 : oFileList.AddString(osFilename.c_str());
1264 : }
1265 : }
1266 14 : return oFileList.StealList();
1267 : }
|