내보내기와 가져오기
이 장은 벡터 데이터를 다른 파일 형식으로 내보내고(Shapefile, GeoJSON, FlatGeobuf), 다른 파일이나 데이터베이스의 테이블을 GeoPackage로 가져오는 방법을 설명합니다. 필드를 형식에 맞추는 필드 계획, 대상이 이미 있을 때와 중간에 실패하거나 취소했을 때 남는 것, 좌표계 변환, 진행 보고와 취소, 결과 객체를 다루고, 형식을 오가며 값이 어떻게 바뀌는지를 표로 정리합니다.
이 장의 코드는 sdk_samples의 transfer 예제에서 가져왔습니다. 실행할 때는 데이터 폴더를 첫 인자로 줍니다(<실행 파일> <sdk_samples/data 폴더>). 예제는 harbor_town.gpkg를 읽기 전용으로만 열고, 내보내는 파일과 가져오기 대상 GeoPackage는 모두 임시 폴더에 쓴 뒤 끝날 때 임시 폴더를 지웁니다. 데이터 폴더의 파일은 바뀌지 않습니다. 이 장은 시작하기의 호환성 확인과 공급자 등록이 끝났다고 가정합니다(초기화와 종료).
예제가 쓰는 데이터는 places(점 12건; name, name_ko(한글), kind, population(NULL 2건)), roads(선 8건; name, lanes, paved), districts(면 5건; name, zone, founded(날짜))이며 좌표계는 EPSG:4326입니다(sdk_samples/data의 README). 데이터셋을 열고 만드는 방법은 4장 데이터셋에, 피처를 읽는 방법은 5장에 있습니다. 이 장의 형식과 함수는 C++에서 gdk_dll/glsGDK.h가 모두 포함합니다.
C#과 다른 점. 관리 래퍼에는 결과 객체를 돌려주는 데이터셋 전송(glsVectorTransferService::Transfer), 스키마 지문(Fingerprint), 스테이징 변형(ExportToStaging, MergeGeoJsonToStaging)이 없습니다. 그 밖의 흐름은 같아서 두 예제의 출력은 같습니다. 언어마다 다른 점은 각 절이 적습니다.
세 가지 길
벡터 데이터를 다른 곳으로 옮기는 길은 세 가지입니다.
| 길 | 호출 | 대상 | 하는 일 |
|---|---|---|---|
| 전송 서비스 | glsVectorTransferService의 Export, Import |
Export: 새 Shapefile, GeoJSON, FlatGeobuf 파일. Import: 이미 있는 GeoPackage나 PostgreSQL 데이터베이스의 새 테이블(또는 바꿀 테이블) |
Export는 파일을 임시 자리에 다 쓴 뒤에 제자리로 옮깁니다(대상이 이미 있을 때). Import는 원본과 대상을 스냅숏으로 받아 쓰기 직전에 다시 확인하고, 데이터셋을 스스로 열고 닫습니다. 둘 다 결과 객체(결과와 경고)를 돌려줍니다 |
| 데이터셋의 가져오기 | glsDataset의 ImportVectorLayer, TransferVectorLayer |
호출자가 쓰기로 연 데이터셋 | 열린 데이터 소스를 받아 그 데이터셋에 테이블을 만들거나(CreateNew), 바꾸거나(ReplaceDestination), TransferVectorLayer로는 덧붙입니다(Append). 결과는 상태와 건수뿐입니다 |
| 직접 쓰기 | 데이터 소스의 AddFeature 등 (5장) |
쓰기로 연 데이터 소스 | 피처를 한 건씩 씁니다. 형식 변환과 필드 대응은 호출자가 합니다 |
두 번째 길은 데이터셋이 트랜잭션을 지원해야 하며(지원하지 않으면 NotSupported), 전송 전체를 그 트랜잭션 안에서 하고 실패하거나 취소되면 트랜잭션을 되돌립니다. 무엇이 되돌려지는지는 공급자의 트랜잭션에 따릅니다. GeoPackage는 만든 테이블까지 되돌리며, 예제는 GeoPackage 대상으로 이것을 보입니다(진행과 취소). Export, Import와 C++의 glsVectorTransferService::Transfer(열린 데이터셋을 빌려 같은 전송을 하고 결과 객체를 돌려줌)도 안에서 이 전송을 씁니다.
고르는 기준은 다음과 같습니다.
- 파일로 내보낼 때는
Export를 씁니다. 대상 파일이 이미 있으면 바꾸며, 실패하거나 취소되면 이전 파일이 그대로 남습니다. - 파일이나 데이터베이스의 테이블을 다른 GeoPackage나 PostgreSQL 데이터베이스로 가져오면서, 고른 뒤에 원본이나 대상이 바뀌었으면 쓰지 않아야 할 때는
Import를 씁니다.Import는 덧붙이기를 하지 않습니다. - 이미 쓰기로 열어 둔 데이터셋에 넣거나, 덧붙이거나, 대상이 GeoPackage와 PostgreSQL이 아닐 때는 데이터셋의
ImportVectorLayer나TransferVectorLayer를 씁니다.
GeoJSON 여러 개를 파일 하나로 합치는 MergeGeoJson, 메모리 데이터셋을 파일로 저장하는 SaveMemoryTablesToFile, PostgreSQL로의 전송은 이 장에서 다루지 않습니다. 자세한 설명은 C++ API 레퍼런스와 .NET API 레퍼런스에 있습니다.
내보내기
Export(source, format, outputPath, options, progress, user, &outcome)는 데이터 소스 하나를 새 파일 하나(Shapefile은 파일 묶음 하나)로 씁니다. 형식은 glsVectorExportFormat(Shapefile, GeoJson, FlatGeobuf)입니다. 원본 데이터 소스는 호출 동안만 빌리며, 호출은 끝날 때까지 돌아오지 않습니다(UI 스레드에서는 스레드를 보세요).
옵션(glsVectorTransferOptions)에서 내보내기가 쓰는 것은 다음과 같습니다.
| 옵션 | 뜻 |
|---|---|
Fields |
쓸 필드의 대응 목록(원본 필드 번호와 출력 필드 정의). 비어 있으면 속성 없이 지오메트리만 씁니다. 형식에 맞는 목록은 필드 계획으로 만듭니다 |
TargetLayerName |
데이터 소스 이름. GeoJSON과 FlatGeobuf는 필요하며 비어 있으면 InvalidArgument입니다. Shapefile은 이 이름이 파일 이름이 됩니다(아래) |
OutputEpsg, OutputSrs |
출력 좌표계. OutputSrs가 우선합니다. GeoJSON은 이 값과 상관없이 EPSG:4326으로 씁니다 |
CreateSpatialIndex |
공간 인덱스를 만들지(기본값 true). Shapefile은 .gdkqix 파일이 생깁니다. FlatGeobuf 파일은 이 값과 상관없이 피처가 있으면 언제나 파일 안에 공간 인덱스를 담습니다 |
ProgressInterval |
진행 보고 간격(피처 수, 기본값 500) |
Mode |
쓰지 않습니다. 내보내기는 언제나 새 데이터 소스를 만듭니다 |
경로. GeoJSON과 FlatGeobuf는 outputPath가 만들 파일입니다. 파일을 쓰는 공급자는 이 경로의 확장자로 정해지므로, 확장자를 형식에 맞춥니다(GeoJSON은 .geojson이나 .json, FlatGeobuf는 .fgb). Shapefile은 outputPath의 폴더에 파일 묶음을 만들고, 이름은 TargetLayerName이 있으면 그것, 없으면 outputPath에서 확장자를 뺀 이름입니다(TargetLayerName은 폴더 구분자가 없는 이름이어야 하며, 아니면 InvalidArgument). 폴더는 미리 있어야 합니다. 없는 폴더를 주면 IOError로 실패하고 아무 파일도 만들지 않습니다. 원본과 같은 파일을 대상으로 주면 NotSupported로 거절합니다.
예제는 places를 Shapefile로 내보낸 뒤 만들어진 파일 목록과 건수(12)를 확인하고, 다시 연 스키마가 원본의 네 필드인지 봅니다. 다시 열 때는 Shapefile 폴더를 shp://<폴더>로 엽니다(URI 형식). 이어서 roads를 GeoJSON으로(8건), districts를 FlatGeobuf로(5건) 내보내고 다시 열어 건수와 필드 형식을 확인합니다.
결과 객체는 glsReleaseVectorTransferOutcome으로 반납합니다. 호출이 실패해도 돌아올 수 있으므로 null이 아니면 반납합니다. 결과를 읽는 호출(GetWarning, GetRecoveryJson)은 마지막 오류 메시지를 지우므로, 실패한 호출의 메시지는 결과를 읽기 전에 복사합니다(예제의 readOutcome). ExportShapefile은 Export를 직접 부르고, 다른 단계는 같은 일을 하는 도우미 exportLayer를 씁니다. Fields의 OutputField.Name 문자열은 호출 동안만 살아 있으면 됩니다. 예제의 도우미 defaultPlan과 planMappings는 원본 스키마로 필드 계획을 만들어 대응 목록으로 바꾸고, allFields는 모든 필드를 원래 이름과 형식으로 대응시킵니다.
// Export writes one data source to a new file. The fields to write come from
// options.Fields: without a mapping the file gets geometry only. The default
// plan of the field policy gives a mapping that the format accepts. For a
// Shapefile the path names the .shp file; with TargetLayerName set, the file
// set is named after it in the same folder. The outcome is released with
// glsReleaseVectorTransferOutcome; reading it clears the last error message,
// so the message of a failed call is copied first (readOutcome does that).
// The other steps call Export through the helper exportLayer, which does the
// same as this function.
static bool exportShapefile(GDK::glsDataSource& places, const Paths& p)
{
PlanPtr plan(nullptr, GDK::glsReleaseExportFieldPlan);
std::vector<GDK::glsVectorTransferFieldMapping> fields;
if (!defaultPlan(places, GDK::glsVectorExportFormat::Shapefile, plan) || !planMappings(*plan, fields)) {
return false;
}
GDK::glsVectorTransferOptions options;
options.TargetLayerName = "places";
options.Fields = fields.data();
options.FieldCount = static_cast<int>(fields.size());
GDK::glsVectorTransferOutcome* raw = nullptr;
const std::string file = pathText(p.shapes / "places.shp");
const GDK::glsStatus status = GDK::glsVectorTransferService::Export(
&places, GDK::glsVectorExportFormat::Shapefile, file.c_str(), &options, nullptr, nullptr, &raw);
OutcomePtr outcome(raw, GDK::glsReleaseVectorTransferOutcome);
Result result;
readOutcome(status, outcome.get(), result);
outcome.reset();
if (!reported(status, result)) {
return false;
}
const std::string files = fileNames(p.shapes);
int64_t count = 0;
std::string schema;
DatasetPtr dataset;
SourcePtr source;
if (!openReadOnly("shp://" + pathText(p.shapes), "places", dataset, source) ||
!succeeded(source->GetFeatureCount(&count)) || !schemaText(*source, schema)) {
return false;
}
std::printf("[sample] places to Shapefile: %s, %s, %" PRId64 " features\n", executionName(result.execution),
evidenceName(result.evidence), result.features);
std::printf("[sample] files: %s\n", files.c_str());
std::printf("[sample] read back: %" PRId64 " features, fields %s\n", count, schema.c_str());
return (result.execution == GDK::glsTransferExecution::Completed &&
result.evidence == GDK::glsTransferEvidence::Committed && result.features == 12 &&
files == "places.cpg places.dbf places.gdkqix places.prj places.shp places.shx" && count == 12 &&
schema == "name:String name_ko:String kind:String population:Int64") ||
unexpected("expected a Shapefile with 12 features");
}
// GeoJSON and FlatGeobuf are one file each; the path is that file and
// TargetLayerName is required. GeoJSON is always written in WGS84
// (EPSG:4326): a source with another valid CRS is reprojected, and a source
// without a valid CRS is refused.
static bool exportGeoJson(GDK::glsDataSource& roads, const Paths& p)
{
std::vector<std::string> names;
std::vector<GDK::glsVectorTransferFieldMapping> fields;
if (!allFields(roads, names, fields)) {
return false;
}
GDK::glsVectorTransferOptions options;
options.TargetLayerName = "roads";
options.Fields = fields.data();
options.FieldCount = static_cast<int>(fields.size());
Result result;
const GDK::glsStatus called = exportLayer(roads, GDK::glsVectorExportFormat::GeoJson, p.folder / "roads.geojson",
options, nullptr, nullptr, result);
if (!reported(called, result)) {
return false;
}
int64_t count = 0;
std::string schema;
DatasetPtr dataset;
SourcePtr source;
if (!openReadOnly(p.geojson, "roads", dataset, source) || !succeeded(source->GetFeatureCount(&count)) ||
!schemaText(*source, schema)) {
return false;
}
std::printf("[sample] roads to GeoJSON: %s, %" PRId64 " features; read back %" PRId64 ", fields %s\n",
executionName(result.execution), result.features, count, schema.c_str());
return (result.execution == GDK::glsTransferExecution::Completed && result.features == 8 && count == 8 &&
schema == "name:String lanes:Int64 paved:Boolean") ||
unexpected("expected a GeoJSON file with 8 features");
}
// FlatGeobuf (like a Shapefile) is written in the source CRS unless
// OutputEpsg or OutputSrs asks for another. A FlatGeobuf file carries its
// spatial index inside the file whatever CreateSpatialIndex says. A Date
// field is written as text and read back as a String field.
static bool exportFlatGeobuf(GDK::glsDataSource& districts, const Paths& p)
{
std::vector<std::string> names;
std::vector<GDK::glsVectorTransferFieldMapping> fields;
if (!allFields(districts, names, fields)) {
return false;
}
GDK::glsVectorTransferOptions options;
options.TargetLayerName = "districts";
options.Fields = fields.data();
options.FieldCount = static_cast<int>(fields.size());
Result result;
const GDK::glsStatus called = exportLayer(districts, GDK::glsVectorExportFormat::FlatGeobuf,
p.folder / "districts.fgb", options, nullptr, nullptr, result);
if (!reported(called, result)) {
return false;
}
int64_t count = 0;
std::string schema;
DatasetPtr dataset;
SourcePtr source;
if (!openReadOnly(p.flatgeobuf, "districts", dataset, source) || !succeeded(source->GetFeatureCount(&count)) ||
!schemaText(*source, schema)) {
return false;
}
std::printf("[sample] districts to FlatGeobuf: %s, %" PRId64 " features; read back %" PRId64 ", fields %s\n",
executionName(result.execution), result.features, count, schema.c_str());
return (result.execution == GDK::glsTransferExecution::Completed && result.features == 5 && count == 5 &&
schema == "name:String zone:String founded:String") ||
unexpected("expected a FlatGeobuf file with 5 features");
}
형식별 차이
| Shapefile | GeoJSON | FlatGeobuf | |
|---|---|---|---|
| 만들어지는 파일 | <이름>.shp, .shx, .dbf, .prj(좌표계가 유효할 때), .cpg, 공간 인덱스를 만들면 .gdkqix |
outputPath 파일 하나 |
outputPath 파일 하나 |
| 좌표계 | 원본 그대로, 또는 OutputEpsg/OutputSrs |
언제나 EPSG:4326. 원본 좌표계가 유효하지 않으면 InvalidArgument |
원본 그대로, 또는 OutputEpsg/OutputSrs |
| 필드 이름 | 10바이트까지. 더 길면 NotSupported. 대소문자만 다른 두 이름은 InvalidArgument |
길이 제한 없음. 대소문자만 다른 두 이름은 AlreadyExists |
길이 제한 없음. 대소문자만 다른 두 이름은 AlreadyExists |
| NULL 허용 | 모든 필드가 NULL을 허용해야 합니다. NULL을 허용하지 않거나 기본값이 있는 필드가 있으면 데이터 소스를 만들지 못해 NotSupported("vector data source creation not supported by this dataset")로 실패합니다. 대응 목록의 출력 필드는 Nullable을 true로 둡니다 |
||
| 필드 형식 | 정수, 실수, 문자열, 날짜, 불리언. Binary, Time, DateTime은 NotSupported |
SDK가 쓴 파일은 필드 형식을 함께 적어 둡니다. 다시 열 때 이 형식을 값에서 짐작한 형식과 합치므로, 정수, 64비트 정수, 실수, 불리언 필드는 첫 피처의 값이 있으면 그대로 돌아오지만 첫 피처의 값이 NULL이거나 값이 모두 NULL이면 문자열 필드가 됩니다. 날짜 필드는 언제나 문자열 필드로 돌아옵니다 | 날짜와 시간(Date, Time)은 텍스트로 쓰여 문자열 필드로 돌아옵니다 |
| 문자 인코딩 | UTF-8로 쓰고 .cpg에 UTF-8을 적습니다 |
UTF-8 | UTF-8 |
| 지오메트리 | 파일 하나에 지오메트리 형식 하나. 원본 데이터 소스의 형식으로 정해집니다 | ||
| M 값 | M 형식(원본 레이어가 M을 반드시 가짐)과 Z 형식의 파일만 담습니다. M이 있어도 되는 2차원 레이어는 M이 없는 형식으로 만들어져 M이 버려지고 경고가 붙습니다 | 담지 못합니다. M이 있는 원본을 내보내면 M이 버려지고 경고가 붙습니다(결과와 경고) | 담습니다 |
필드 이름은 모든 형식에서 비어 있지 않고 서로 달라야 하며, 빈 이름이나 똑같은 이름이 있으면 InvalidArgument로 실패합니다. ASCII 대소문자만 다른 두 이름(Name과 name)도 모든 형식에서 같은 이름으로 봅니다. Shapefile은 이것을 InvalidArgument로, GeoJSON과 FlatGeobuf는 AlreadyExists로 거절합니다. GeoJSON과 FlatGeobuf의 필드 계획 검사(Validate)는 이름을 정확히 비교하므로 이 경우를 DuplicateName으로 알리지 않습니다. 또 FID 열과 지오메트리 열의 이름인 fid, geom(대소문자 무시)은 필드 이름으로 쓸 수 없으며 InvalidArgument입니다.
Shapefile의 문자열 필드 폭은 바이트 수이며 254바이트까지입니다. GeoPackage처럼 문자열 폭을 글자 수로 보는 원본에서 내보낼 때는, 폭을 정한 문자열 필드의 폭을 UTF-8 바이트로 세 배(최대 254) 늘려서 만듭니다. 예제의 기본 계획은 폭 80이므로 .dbf의 필드 폭은 240바이트가 됩니다. 값이 필드 폭보다 길면 그 쓰기가 InvalidArgument로 실패하고 내보내기 전체가 실패합니다. 폭을 값에 맞추려면 필드 계획의 폭 조사를 씁니다. 폭 조사가 준 문자열 폭을 바이트 수 그대로 쓰려면 대응 목록의 OutputField.Width에 음수(-폭, -254까지)를 줍니다. GeoJSON과 FlatGeobuf로 내보낼 때 음수 폭은 InvalidArgument입니다.
형식이 달라서 값이 바뀌는 경우는 왕복했을 때 달라지는 값에 모았습니다.
필드 계획
glsExportFieldPolicy는 필드 목록(glsExportFieldOptions: 원본 필드 번호, 이름, 형식, 폭, 자릿수, NULL 허용, 포함 여부)을 형식에 맞게 고칩니다. 결과는 필드 계획(glsExportFieldPlan)이며, 필드마다 고친 값(GetField), 원래 값(GetOriginalField), 무엇이 바뀌었는지(GetIssue, glsExportFieldIssue)를 줍니다.
| 호출 | 하는 일 |
|---|---|
BuildDefaults(format, fields, count, &plan) |
기본 계획. Shapefile이면 아래 규칙으로 이름과 폭을 고칩니다. GeoJSON과 FlatGeobuf는 받은 값을 그대로 둡니다 |
NormalizeName(format, name, ...) |
이름 하나를 같은 규칙으로 고칩니다 |
NormalizeField(format, previousType, field, &plan) |
필드 하나의 폭과 자릿수를 고칩니다(형식을 바꾼 뒤 등) |
Validate(format, fields, count, &plan) |
고치지 않고 문제만 찾습니다(빈 이름 EmptyName, 중복 DuplicateName, 지원하지 않는 형식 UnsupportedType, 10바이트를 넘는 Shapefile 이름 NameTooLong, 맞지 않는 폭 InvalidLayout) |
ScanWidths(source, fields, count, progress, user, &plan, &issue, &index) |
원본의 값을 모두 읽어 정수와 문자열 필드의 폭을 값에 맞춥니다(다른 형식의 필드를 주면 InvalidSelection, 원본 필드와 형식이 다르면 TypeMismatch로 실패). 문자열은 가장 긴 값의 UTF-8 바이트 수(254를 넘으면 ValueTooWide로 실패), 정수는 가장 긴 자릿수(64비트 정수는 10 이상)입니다. 값이 있는 문자열 필드는 ExactStringByteWidth가 true가 되고, 값이 모두 NULL인 필드는 GetAllNull이 true입니다(형식별 차이). 실패하면 문제와 필드 번호를 주고 계획은 만들지 않습니다. 진행 콜백은 부른 스레드에서 불리고 false를 돌려주면 취소됩니다 |
IsSupported(format, type) |
형식이 그 필드 형식을 담는지 |
Shapefile 이름 규칙. 앞뒤 공백을 지우고, 글자·숫자·_가 아닌 문자를 _로 바꾸고, 숫자로 시작하면 앞에 F를 붙이고, 비면 FIELD로 하고, 10바이트(UTF-8)까지 자릅니다(글자를 가운데에서 자르지 않습니다). 대소문자를 무시하고 같은 이름이 나오면 번호를 붙이며, 붙인 결과가 10바이트를 넘으면 그만큼 앞부분을 줄입니다(abc는 abc1, population은 populatio1). 한글 이름은 그대로 두지만 한 글자가 3바이트이므로, 예를 들어 2020 인구는 F2020_인이 됩니다. 이름이 바뀌면 NameChanged입니다.
Shapefile 폭 규칙. 날짜는 8, 불리언은 1로 고정합니다. 그 밖에는 폭을 정한(WidthSpecified) 필드는 254까지의 그 값을, 아니면 기본값(정수 10, 64비트 정수와 실수 18, 문자열 80)을 씁니다. 실수의 기본 자릿수는 6입니다. 폭이나 자릿수가 바뀌면 LayoutChanged입니다(이름도 바뀌면 NameChanged가 우선). Binary, Time, DateTime 필드는 UnsupportedType이 되고 Include가 false가 됩니다. 계획은 Nullable을 바꾸지 않으므로, 원본에 NULL을 허용하지 않는 필드가 있으면 대응 목록에서 Nullable을 true로 바꿔야 Shapefile로 내보낼 수 있습니다(형식별 차이). 계획에서 대응 목록을 만들 때는 Include가 true인 필드만 넣습니다. 예제의 도우미는 Shapefile 계획의 필드를 모두 Nullable true로 넣습니다.
glsExportFieldIssue의 값이 고정되어 있다는 약속은 없습니다(값이 고정된 열거형). 이름으로 비교하세요.
예제는 places의 Shapefile 계획을 출력합니다. 계획이 정한 이름이 실제로 파일에 쓰이는 것은 예제가 보여 주지 않습니다(예제의 필드 이름은 바뀌지 않습니다). GeoPackage는 정수 필드를 Int64로 알려 주므로 population은 Int64(18)이 되고, 폭이 없던 문자열 필드는 String(80)이 되어 네 필드 모두 LayoutChanged입니다. 이름이 바뀌는 필드는 없으므로, 긴 이름 둘(population total, population-change)로 따로 계획을 만들어 population과 populatio1이 되는 것을 확인합니다.
계획은 glsReleaseExportFieldPlan으로 반납합니다. GetField가 주는 Name은 계획을 반납할 때까지 유효합니다. 입력 glsExportFieldOptions의 StructSize는 기본값 그대로 두어야 합니다(다른 값이면 호출이 실패합니다). 예제의 도우미 sourceFields는 원본 스키마의 이름, 형식, 폭, 자릿수, NULL 허용을 옵션으로 옮깁니다.
// BuildDefaults turns field options into what a format can store. For a
// Shapefile it shortens names to 10 bytes and replaces characters other than
// letters, digits and '_', numbers names that would collide, and fills in
// widths; GetIssue says what changed. Here the places fields need no new
// name, and two long names show the renaming.
static bool fieldPlan(GDK::glsDataSource& places)
{
PlanPtr plan(nullptr, GDK::glsReleaseExportFieldPlan);
if (!defaultPlan(places, GDK::glsVectorExportFormat::Shapefile, plan)) {
return false;
}
std::string text;
int renamed = 0;
for (int i = 0; i < plan->GetFieldCount(); ++i) {
GDK::glsExportFieldOptions f;
GDK::glsExportFieldIssue issue = GDK::glsExportFieldIssue::None;
if (!succeeded(plan->GetField(i, &f)) || !succeeded(plan->GetIssue(i, &issue))) {
return false;
}
renamed += issue == GDK::glsExportFieldIssue::NameChanged ? 1 : 0;
text += (text.empty() ? "" : ", ") + std::string(f.Name) + " " + fieldTypeName(f.Type) + "(" +
std::to_string(f.Width) + ") " + issueName(issue);
}
std::printf("[sample] Shapefile plan for places: %s\n", text.c_str());
GDK::glsExportFieldOptions longNames[2];
longNames[0].SourceIndex = 0;
longNames[0].Name = "population total";
longNames[0].Type = GDK::glsFieldType::Integer;
longNames[1].SourceIndex = 1;
longNames[1].Name = "population-change";
longNames[1].Type = GDK::glsFieldType::Integer;
GDK::glsExportFieldPlan* raw = nullptr;
if (!succeeded(GDK::glsExportFieldPolicy::BuildDefaults(GDK::glsVectorExportFormat::Shapefile, longNames, 2,
&raw))) {
return false;
}
PlanPtr renamedPlan(raw, GDK::glsReleaseExportFieldPlan);
GDK::glsExportFieldOptions first;
GDK::glsExportFieldOptions second;
GDK::glsExportFieldIssue firstIssue = GDK::glsExportFieldIssue::None;
GDK::glsExportFieldIssue secondIssue = GDK::glsExportFieldIssue::None;
if (!succeeded(renamedPlan->GetField(0, &first)) || !succeeded(renamedPlan->GetField(1, &second)) ||
!succeeded(renamedPlan->GetIssue(0, &firstIssue)) || !succeeded(renamedPlan->GetIssue(1, &secondIssue))) {
return false;
}
std::printf("[sample] 'population total' -> %s (%s), 'population-change' -> %s (%s)\n", first.Name,
issueName(firstIssue), second.Name, issueName(secondIssue));
return (renamed == 0 &&
text == "name String(80) LayoutChanged, name_ko String(80) LayoutChanged, kind String(80) "
"LayoutChanged, population Int64(18) LayoutChanged" &&
std::strcmp(first.Name, "population") == 0 && std::strcmp(second.Name, "populatio1") == 0 &&
firstIssue == GDK::glsExportFieldIssue::NameChanged &&
secondIssue == GDK::glsExportFieldIssue::NameChanged) ||
unexpected("expected the default Shapefile plan");
}
대상이 이미 있을 때와 실패했을 때
Export는 대상 파일이 이미 있으면 바꿉니다. 순서는 다음과 같습니다.
- 대상 폴더 안에 임시 폴더를 만들고, 대상의 지금 상태(있는지, 크기, 수정 시각)를 기록합니다.
- 새 파일을 임시 폴더에 다 쓰고 닫습니다. 이 단계가 실패하거나 취소되면 임시 폴더를 지우고 끝나며, 대상은 건드리지 않습니다.
- 대상이 기록한 상태 그대로인지 확인한 뒤, 이전 파일을 임시 폴더로 옮기고 새 파일을 제자리로 옮깁니다. Shapefile은 묶음 전체(
.shp,.shx,.dbf,.prj,.cpg,.gdkqix,.qix,.sbn,.sbx가운데 있는 것)를 옮깁니다. 이전 묶음에만 있던 파일도 치워집니다. - 다 옮기면 이전 파일과 임시 폴더를 지웁니다. 옮기는 도중 실패하면 옮긴 것을 되돌립니다.
그래서 내보내기가 실패하거나 취소되어도 대상 이름의 파일은 반쯤 쓴 것으로 바뀌지 않고, 이전 파일이 그대로 남습니다. 예외가 둘 있습니다. 되돌리기마저 실패하면 결과의 근거는 Partial이고 복구 보고서(결과와 경고)에 이전 파일을 옮겨 둔 자리가 적힙니다. 또 임시 폴더를 지우지 못하면(예: 그 안의 파일이 잠겨 있을 때) 임시 폴더(.gdk-export-로 시작하는 이름)가 대상 폴더에 남습니다. 게시가 끝난 뒤라면 결과의 경고에 Output committed; staging cleanup failed가 붙지만, 실패하거나 취소된 내보내기의 결과는 이것을 알리지 않습니다. 이전 파일을 옮기지 못하면(예: 응용 프로그램이 그 Shapefile을 데이터셋으로 열어 두었을 때) IOError로 실패하고(실행 Failed) 이미 옮긴 파일을 되돌립니다. 첫 파일부터 옮기지 못했으면 근거는 NotStarted이고, Shapefile 묶음에서 몇 파일을 옮긴 뒤 실패해 모두 되돌렸으면 RolledBack입니다. 두 경우 모두 이전 파일은 제자리에 남습니다. 되돌리기마저 실패하면 앞에서 말한 Partial입니다. 대상 파일을 연 데이터셋은 반납한 뒤에 내보내세요. 예제는 취소된 내보내기만 보여 주며, 실패한 내보내기가 남기는 것은 보여 주지 않습니다.
래스터의 ExportGeoTiff는 이미 있는 파일을 바꾸지 않습니다(래스터 만들기). 벡터 내보내기와 규칙이 다릅니다.
예제는 places를 같은 Shapefile에 한 번 더 내보내되 kind 필드를 빼서, 다시 연 스키마가 세 필드로 바뀐 것을 확인합니다. 세 번째 내보내기는 피처를 쓰기 시작할 때(Writing 단계) 진행 콜백이 false를 돌려 취소합니다. 결과는 Cancelled, 실행 Cancelled, 근거 NotStarted이고, 파일 목록과 스키마(세 필드, 12건)는 두 번째 내보내기 그대로이며, 대상 폴더에 남은 폴더는 없습니다.
// An export to a target that exists replaces it: the new files are written
// to a staging folder next to the target and moved in place only after they
// are complete, and the old set is removed. Here the second export leaves out
// the kind field, so the file has three fields afterwards. A third export is
// cancelled while it writes: it ends with Cancelled before anything was moved,
// and the files of the second export stay as they were.
static bool exportTwice(GDK::glsDataSource& places, const Paths& p)
{
PlanPtr plan(nullptr, GDK::glsReleaseExportFieldPlan);
std::vector<GDK::glsVectorTransferFieldMapping> fields;
if (!defaultPlan(places, GDK::glsVectorExportFormat::Shapefile, plan) || !planMappings(*plan, fields)) {
return false;
}
fields.erase(fields.begin() + 2); // kind
GDK::glsVectorTransferOptions options;
options.TargetLayerName = "places";
options.Fields = fields.data();
options.FieldCount = static_cast<int>(fields.size());
const std::filesystem::path file = p.shapes / "places.shp";
const std::string uri = "shp://" + pathText(p.shapes);
Result second;
const GDK::glsStatus called = exportLayer(places, GDK::glsVectorExportFormat::Shapefile, file, options, nullptr,
nullptr, second);
if (!reported(called, second)) {
return false;
}
std::string afterSecond;
{
DatasetPtr dataset;
SourcePtr source;
if (!openReadOnly(uri, "places", dataset, source) || !schemaText(*source, afterSecond)) {
return false;
}
}
std::printf("[sample] export to the same path again: %s, %s; fields %s\n", executionName(second.execution),
evidenceName(second.evidence), afterSecond.c_str());
options.Fields = fields.data();
options.FieldCount = 1; // only the name: would change the file if it were published
Result third;
const GDK::glsStatus status = exportLayer(places, GDK::glsVectorExportFormat::Shapefile, file, options,
cancelWhenWriting, nullptr, third);
const bool cancelled = status.Code == GDK::glsResultCode::Cancelled;
if (!status.IsOk() && !cancelled) {
return reported(status, third); // another failure: print it and stop
}
std::string afterThird;
int64_t count = 0;
{
DatasetPtr dataset;
SourcePtr source;
if (!openReadOnly(uri, "places", dataset, source) || !schemaText(*source, afterThird) ||
!succeeded(source->GetFeatureCount(&count))) {
return false;
}
}
const std::string files = fileNames(p.shapes);
const int folders = folderCount(p.shapes);
std::printf("[sample] cancelled export: %s, %s, %s; fields %s, %" PRId64 " features\n",
cancelled ? "Cancelled" : "not cancelled", executionName(third.execution),
evidenceName(third.evidence), afterThird.c_str(), count);
std::printf("[sample] files: %s; folders left: %d\n", files.c_str(), folders);
return (second.execution == GDK::glsTransferExecution::Completed &&
second.evidence == GDK::glsTransferEvidence::Committed &&
afterSecond == "name:String name_ko:String population:Int64" && cancelled &&
third.execution == GDK::glsTransferExecution::Cancelled &&
third.evidence == GDK::glsTransferEvidence::NotStarted && afterThird == afterSecond && count == 12 &&
files == "places.cpg places.dbf places.gdkqix places.prj places.shp places.shx" && folders == 0) ||
unexpected("expected the second export in place and the cancelled one without effect");
}
가져오기
Import는 한 파일이나 데이터베이스의 테이블을 다른 GeoPackage나 PostgreSQL 데이터베이스의 테이블로 복사합니다. 순서는 두 단계입니다.
Inspect(uri, table, &snapshot)로 원본과 대상을 하나씩 스냅숏으로 잡습니다. 스냅숏은 테이블이 있는지(GetExists), 지오메트리가 있는 보통 벡터 테이블인지(GetOrdinarySpatialVector), 스키마 지문, 물리적인 파일·데이터베이스의 신원을 담습니다.Inspect는 데이터셋을 읽기 전용으로 열었다가 닫으며, 스냅숏은 열린 데이터셋을 붙잡지 않습니다. 대상 테이블은 아직 없어도 되지만 대상 파일은 있어야 합니다. 없는 GeoPackage 파일은IOError로 실패하고 파일을 만들지 않습니다.Import(request, progress, user, &outcome)에 두 스냅숏과 전송 옵션을 줍니다.Import는 원본을 읽기 전용으로, 대상을 쓰기로 따로 열고, 열 때와 쓰기 직전에 두 스냅숏과 지금 상태를 다시 비교해 무엇이든 바뀌었으면InvalidArgument로 쓰지 않습니다. 다 끝나면 연 데이터셋을 닫습니다.
Import가 거절하는 경우는 다음과 같습니다. 거절된 결과는 실행 Rejected, 근거 NotStarted이며 대상은 바뀌지 않습니다.
| 경우 | 결과 |
|---|---|
| 대상이 GeoPackage나 PostgreSQL이 아님 | NotSupported |
| 원본이 지오메트리가 있는 보통 벡터 테이블이 아님 | NotSupported |
| 원본과 대상이 다른 데이터베이스라고 확인되지 않음(같은 파일 포함) | NotSupported |
TargetLayerName이 대상 스냅숏의 테이블 이름과 다름 |
InvalidArgument |
Mode가 Append |
NotSupported(가져오기는 CreateNew와 ReplaceDestination만) |
CreateNew인데 대상 테이블이 이미 있음 |
InvalidArgument |
ReplaceDestination인데 대상이 보통 벡터 테이블로 없음 |
NotSupported |
ReplaceDestination은 대상 테이블을 지우고 새로 만드는 일을 한 트랜잭션에서 하므로, 실패하거나 취소되면 원래 테이블이 남습니다.
예제는 앞에서 내보낸 GeoJSON의 도로를 새 GeoPackage imported.gpkg의 roads 테이블로 가져옵니다. 예제는 대상 GeoPackage를 먼저 만들고(만들기) 반납해 둡니다. 원본 스냅숏은 있고(true) 대상 스냅숏은 없음(false)을 확인하고, 결과가 Completed, Committed, 8건이며 다시 열어도 8건인지 확인합니다.
요청은 glsVectorImportOptionsV1(Source, Target, Transfer, FidPolicy)입니다. StructSize는 기본값 그대로 둡니다. FidPolicy가 null이거나 기본값(Generate)이면 대상이 피처 번호를 새로 매깁니다. 스냅숏은 glsReleaseVectorTransferSnapshot으로, 결과는 glsReleaseVectorTransferOutcome으로 반납합니다. 예제의 inspectPair가 스냅숏 둘을 잡습니다. ImportToGeoPackage는 Import를 직접 부르고, 다른 가져오기는 같은 일을 하는 도우미 importLayer를 씁니다.
// Import copies a table from one file or database into another. Both sides
// are first captured with Inspect (the target table need not exist yet);
// Import checks them again just before it writes and refuses when either has
// changed, and when both name the same database. The target must be a
// GeoPackage or PostgreSQL database that exists. CreateNew refuses a target
// table that exists. The request is a glsVectorImportOptionsV1; a FID policy
// left at Generate lets the target number the features. The snapshots and the
// outcome are released by the caller. The other imports go through the helper
// importLayer, which does the same as this function.
static bool importToGeoPackage(GDK::glsDataSource& roadsInGeoJson, const Paths& p)
{
SnapshotPtr source(nullptr, GDK::glsReleaseVectorTransferSnapshot);
SnapshotPtr target(nullptr, GDK::glsReleaseVectorTransferSnapshot);
if (!inspectPair(p.geojson, "roads", p.imported, "roads", source, target)) {
return false;
}
std::printf("[sample] snapshots: source exists %s, target exists %s\n", source->GetExists() ? "true" : "false",
target->GetExists() ? "true" : "false");
std::vector<std::string> names;
std::vector<GDK::glsVectorTransferFieldMapping> fields;
if (!allFields(roadsInGeoJson, names, fields)) {
return false;
}
GDK::glsVectorTransferOptions options;
options.TargetLayerName = "roads";
options.Mode = GDK::glsVectorTransferMode::CreateNew;
options.Fields = fields.data();
options.FieldCount = static_cast<int>(fields.size());
GDK::glsVectorTransferFidPolicy fid;
GDK::glsVectorImportOptionsV1 request;
request.Source = source.get();
request.Target = target.get();
request.Transfer = &options;
request.FidPolicy = &fid;
GDK::glsVectorTransferOutcome* raw = nullptr;
const GDK::glsStatus status = GDK::glsVectorTransferService::Import(&request, nullptr, nullptr, &raw);
OutcomePtr outcome(raw, GDK::glsReleaseVectorTransferOutcome);
Result result;
readOutcome(status, outcome.get(), result);
outcome.reset();
if (!reported(status, result)) {
return false;
}
int64_t count = 0;
if (!countFeatures(p.imported, "roads", count)) {
return false;
}
std::printf("[sample] GeoJSON roads into GeoPackage: %s, %s, %" PRId64 " features; read back %" PRId64 "\n",
executionName(result.execution), evidenceName(result.evidence), result.features, count);
return (source->GetExists() && !target->GetExists() && result.execution == GDK::glsTransferExecution::Completed &&
result.evidence == GDK::glsTransferEvidence::Committed && result.features == 8 && count == 8) ||
unexpected("expected 8 roads in the GeoPackage");
}
필드 대응
필드 대응 목록의 항목 하나는 원본 필드 번호와 출력 필드 정의(이름, 형식, 폭, NULL 허용, 자릿수)입니다. 목록에 없는 원본 필드는 옮기지 않고, 목록이 비어 있으면 속성 없이 지오메트리만 옮깁니다. 같은 규칙이 Export, Import, ImportVectorLayer, TransferVectorLayer에 모두 적용됩니다.
출력 형식이 원본과 다르면 값을 바꿉니다. 정수와 실수 필드는 숫자나 숫자 텍스트를, 불리언 필드는 숫자나 true/false, 1/0, yes/no 텍스트를 받습니다. 바꿀 수 없거나 범위를 넘는 값(예: 정수 필드에 abc)은 NULL이 되고 결과의 변환 실패 건수(ConversionFailureCount)에 셉니다. 문자열, 날짜, 시간 필드는 값을 텍스트로 씁니다. NULL은 NULL로 옮깁니다.
ImportVectorLayer(source, options, progress, user, &result)는 쓰기로 연 데이터셋의 멤버입니다. 옵션(glsBulkImportOptions)은 대상 테이블 이름(TargetTableName, 필요), ReplaceDestination(false면 새로 만들기, 이미 있으면 AlreadyExists), CreateSpatialIndex, OutputEpsg, 대응 목록(glsBulkImportFieldMapping), ProgressInterval입니다. TransferVectorLayer는 glsVectorTransferOptions를 받아 Mode에 Append(대상 테이블이 없으면 NotFound)와 OutputSrs를 더 쓸 수 있습니다. 덧붙이기에서는 대응 목록의 항목 수가 대상 테이블의 필드 수와 같아야 하고, 출력 이름은 대상에 있는 필드 이름이어야 하며, 공간 인덱스는 만들지 않습니다.
예제는 FlatGeobuf로 내보낸 구역을 ImportVectorLayer로 imported.gpkg의 districts로 가져옵니다. name은 district로 이름을 바꾸고, zone은 빼고, founded는 날짜 필드로 옮깁니다. 결과는 5건, 변환 실패 0건이고 새 테이블의 필드는 district:String founded:Date입니다.
glsBulkImportResult는 성공했을 때 옮긴 건수와 변환 실패 건수를 담습니다. 진행 콜백의 형식은 glsBulkImportProgressCallback이며 단계 이름을 텍스트(Phase, 콜백 안에서만 유효)로 받습니다.
// ImportVectorLayer of a dataset opened for writing takes the data source
// itself. Each mapping names a source field by index and the field it
// becomes; fields without a mapping are left out. Here name becomes
// district, zone is left out, and founded is copied.
static bool importWithMapping(const Paths& p)
{
DatasetPtr fgb;
SourcePtr districts;
if (!openReadOnly(p.flatgeobuf, "districts", fgb, districts)) {
return false;
}
int name = -1;
int founded = -1;
if (!fieldIndex(*districts, "name", name) || !fieldIndex(*districts, "founded", founded)) {
return false;
}
if (name < 0 || founded < 0) {
return unexpected("expected the fields name and founded");
}
GDK::glsBulkImportFieldMapping fields[2];
fields[0].SourceFieldIndex = name;
fields[0].OutputField.Name = "district";
fields[0].OutputField.Type = GDK::glsFieldType::String;
fields[1].SourceFieldIndex = founded;
fields[1].OutputField.Name = "founded";
fields[1].OutputField.Type = GDK::glsFieldType::Date;
GDK::glsBulkImportOptions options;
options.TargetTableName = "districts";
options.Fields = fields;
options.FieldCount = 2;
GDK::glsDataset* raw = nullptr;
if (!succeeded(GDK::glsOpenDataset(p.imported.c_str(), &raw))) {
return false;
}
DatasetPtr target(raw);
GDK::glsBulkImportResult result;
if (!succeeded(target->ImportVectorLayer(districts.get(), &options, nullptr, nullptr, &result))) {
return false;
}
GDK::glsDataSource* rawSource = nullptr;
if (!succeeded(target->OpenVectorDataSourceByName("districts", &rawSource))) {
return false;
}
SourcePtr imported(rawSource);
std::string schema;
int64_t count = 0;
if (!schemaText(*imported, schema) || !succeeded(imported->GetFeatureCount(&count))) {
return false;
}
std::printf("[sample] districts with a mapping: %" PRId64 " features, %" PRId64
" conversion failures; fields %s; read back %" PRId64 "\n",
result.FeatureCount, result.ConversionFailureCount, schema.c_str(), count);
return (result.FeatureCount == 5 && result.ConversionFailureCount == 0 &&
schema == "district:String founded:Date" && count == 5) ||
unexpected("expected two fields and 5 districts");
}
좌표계 변환
OutputEpsg나 OutputSrs(둘 다 주면 OutputSrs)를 주면 피처를 쓰면서 지오메트리를 그 좌표계로 바꾸고, 새 테이블은 그 좌표계로 만듭니다. 0이면 원본 좌표계를 씁니다. 잘못된 EPSG 코드는 InvalidArgument입니다. 원본 좌표계가 유효하지 않을 때 Import는 변환을 InvalidArgument로 거절합니다. 데이터셋의 ImportVectorLayer와 TransferVectorLayer는 이때 좌표를 바꾸지 않은 채 요청한 좌표계로 테이블을 만듭니다. 덧붙이기(Append)는 대상 테이블의 좌표계를 씁니다. ImportVectorLayer의 옵션에는 OutputSrs가 없습니다.
예제는 원본 GeoPackage의 places를 Import로 imported.gpkg의 places_3857(Web Mercator, EPSG:3857)로 가져와, 새 테이블의 좌표계가 EPSG:3857인지와 Lighthouse Pier(경도 10.010, 위도 50.010)의 좌표가 구면 메르카토르 식 x = R * lon * π / 180, y = R * ln(tan(π / 4 + lat * π / 360))(R = 6378137)과 0.001미터 안에서 같은지 확인합니다.
// OutputEpsg (or OutputSrs, which takes precedence) reprojects the features
// while they are written; Import refuses it for a source without a valid CRS. Here the places
// of the shipped GeoPackage go to Web Mercator (EPSG:3857), and the point of
// Lighthouse Pier is compared with the spherical Mercator formula.
static bool importReprojected(GDK::glsDataSource& places, const Paths& p)
{
SnapshotPtr source(nullptr, GDK::glsReleaseVectorTransferSnapshot);
SnapshotPtr target(nullptr, GDK::glsReleaseVectorTransferSnapshot);
if (!inspectPair(p.harbor, "places", p.imported, "places_3857", source, target)) {
return false;
}
std::vector<std::string> names;
std::vector<GDK::glsVectorTransferFieldMapping> fields;
if (!allFields(places, names, fields)) {
return false;
}
GDK::glsVectorTransferOptions options;
options.TargetLayerName = "places_3857";
options.OutputEpsg = 3857;
options.Fields = fields.data();
options.FieldCount = static_cast<int>(fields.size());
Result result;
const GDK::glsStatus called = importLayer(*source, *target, options, nullptr, nullptr, result);
if (!reported(called, result)) {
return false;
}
DatasetPtr dataset;
SourcePtr imported;
if (!openReadOnly(p.imported, "places_3857", dataset, imported)) {
return false;
}
GDK::glsSpatialReference* rawSrs = nullptr;
if (!succeeded(imported->GetCrs(&rawSrs))) {
return false;
}
SrsPtr srs(rawSrs, GDK::glsReleaseSpatialReference);
int epsg = 0;
if (!srs || !succeeded(srs->GetEpsgCode(&epsg))) {
return srs ? false : unexpected("expected a CRS");
}
GDK::glsFeatureQuery query;
query.WhereClause = "name = 'Lighthouse Pier'";
GDK::glsFeatureCursor* rawCursor = nullptr;
if (!succeeded(imported->GetFeatures(&query, &rawCursor))) {
return false;
}
CursorPtr cursor(rawCursor);
GDK::glsFeature feature;
bool has = false;
if (!succeeded(cursor->Next(&feature, &has))) {
return false;
}
if (!has) {
return unexpected("expected Lighthouse Pier");
}
GDK::glsGeometry* rawGeometry = nullptr;
if (!succeeded(feature.GetGeometry(&rawGeometry))) {
return false;
}
GeometryPtr geometry(rawGeometry);
GDK::glsEnvelope e;
if (!geometry || !succeeded(geometry->GetEnvelope(&e))) {
return geometry ? false : unexpected("expected a geometry");
}
const double radius = 6378137.0;
const double pi = 3.14159265358979323846;
const double x = radius * 10.010 * pi / 180.0;
const double y = radius * std::log(std::tan(pi / 4.0 + 50.010 * pi / 360.0));
std::printf("[sample] places in EPSG:%d: %" PRId64 " features; Lighthouse Pier %.1f %.1f (formula %.1f %.1f)\n",
epsg, result.features, e.MinX, e.MinY, x, y);
return (epsg == 3857 && result.features == 12 && std::fabs(e.MinX - x) < 0.001 && std::fabs(e.MinY - y) < 0.001) ||
unexpected("expected Web Mercator coordinates");
}
진행과 취소
전송 서비스의 진행 콜백은 glsTransferProgress(단계 glsTransferPhase, Current, Total, Total이 0보다 클 때 true인 Determinate)를 받고, 호출한 스레드에서 불립니다. 데이터셋의 ImportVectorLayer와 TransferVectorLayer의 콜백도 호출한 스레드에서 불리며, 단계를 이름 텍스트로 받습니다.
단계는 Preparing(준비), Writing(피처 쓰기), SpatialIndex(공간 인덱스를 만들 때), Committing(확정), Complete(끝) 순서입니다. Writing은 처음에 한 번(Current 0), 그 뒤로 ProgressInterval개마다, 그리고 마지막 피처에서 불립니다. Export는 임시 파일을 다 쓴 뒤 Finalizing, 제자리로 옮기기 직전에 Publishing, 옮긴 뒤에 Complete를 보냅니다. 예를 들어 도로 8건을 Shapefile로 내보내면 Preparing, Writing 0/8, Writing 8/8, SpatialIndex, Committing, Finalizing, Publishing, Complete 순서로 불립니다.
콜백이 false를 돌려주면 취소를 요청합니다.
Complete전이면 호출은Cancelled로 끝납니다. 데이터셋 전송은 트랜잭션을 되돌립니다. 대상을 건드리기 전(예: 처음Preparing보고)에 멈추면 근거는NotStarted입니다. 쓰기 시작한 뒤에 멈추면 근거는 공급자가 되돌리기를 확인해 주면RolledBack, 아니면Unknown입니다. GeoPackage와 PostgreSQL 대상은 확인해 주며, GeoPackage는 만든 테이블과 쓴 피처를 남기지 않습니다.Export는 임시 파일을 지우고 대상은 건드리지 않습니다(근거NotStarted).Publishing에서 취소해도 옮기기 전이므로 같습니다.Complete에서는 이미 확정된 뒤라 취소되지 않고 호출은 성공합니다.Export는 결과에 그 사실을 경고로 남깁니다(결과와 경고).- 전송 서비스에 준 C++ 콜백이 예외를 던지면 SDK가 잡아 취소로 다루고 결과의
GetCallbackFailed가true가 됩니다.
예제는 ProgressInterval을 1로 두고, GeoJSON의 도로를 imported.gpkg의 roads_cancelled로 가져오다가 네 번째 피처를 쓴 뒤(8건 중 4건) 멈춥니다. 결과는 Cancelled, 실행 Cancelled, 근거 RolledBack이고, 다시 잡은 스냅숏으로 roads_cancelled가 없음을, 데이터셋으로 테이블이 앞의 세 개(roads, districts, places_3857)뿐임을 확인합니다. 데이터셋의 ImportVectorLayer도 같은 트랜잭션 전송을 쓰므로, 콜백이 false를 돌려주면 Cancelled로 끝납니다.
콜백은 glsTransferProgressCallback(bool(*)(const glsTransferProgress*, void*))입니다. 마지막 인자는 호출에 준 user 포인터입니다. 예제는 캡처 없는 람다를 콜백으로 쓰고, 상태는 user 포인터로 넘깁니다.
// The progress callback runs on the thread that called Import. Returning
// false asks the transfer to stop: it ends with Cancelled and rolls back, so
// the table it had created and the rows it had written are gone. With
// ProgressInterval 1 the callback sees every written feature; here it stops
// after the fourth. A callback is a plain function; a lambda without
// captures converts to one, and the user pointer carries the state.
static bool importCancel(GDK::glsDataSource& roadsInGeoJson, const Paths& p)
{
const GDK::glsTransferProgressCallback stopAfterFour = [](const GDK::glsTransferProgress* progress,
void* user) -> bool {
auto& state = *static_cast<CancelState*>(user);
if (progress->Phase == GDK::glsTransferPhase::Writing && progress->Current >= 4) {
state.stoppedAt = progress->Current;
state.total = progress->Total;
return false;
}
return true;
};
SnapshotPtr source(nullptr, GDK::glsReleaseVectorTransferSnapshot);
SnapshotPtr target(nullptr, GDK::glsReleaseVectorTransferSnapshot);
if (!inspectPair(p.geojson, "roads", p.imported, "roads_cancelled", source, target)) {
return false;
}
std::vector<std::string> names;
std::vector<GDK::glsVectorTransferFieldMapping> fields;
if (!allFields(roadsInGeoJson, names, fields)) {
return false;
}
GDK::glsVectorTransferOptions options;
options.TargetLayerName = "roads_cancelled";
options.Fields = fields.data();
options.FieldCount = static_cast<int>(fields.size());
options.ProgressInterval = 1;
CancelState state;
Result result;
const GDK::glsStatus status = importLayer(*source, *target, options, stopAfterFour, &state, result);
const bool cancelled = status.Code == GDK::glsResultCode::Cancelled;
if (!status.IsOk() && !cancelled) {
return reported(status, result); // another failure: print it and stop
}
GDK::glsVectorTransferSnapshot* raw = nullptr;
if (!succeeded(GDK::glsVectorTransferService::Inspect(p.imported.c_str(), "roads_cancelled", &raw))) {
return false;
}
SnapshotPtr after(raw, GDK::glsReleaseVectorTransferSnapshot);
int tables = 0;
{
GDK::glsDataset* rawDataset = nullptr;
if (!succeeded(GDK::glsOpenDatasetReadOnly(p.imported.c_str(), &rawDataset))) {
return false;
}
DatasetPtr dataset(rawDataset);
if (!succeeded(dataset->GetDataSourceCount(&tables))) {
return false;
}
}
std::printf("[sample] callback stopped at %" PRId64 " of %" PRId64 ": %s, %s, %s\n", state.stoppedAt,
state.total, cancelled ? "Cancelled" : "not cancelled", executionName(result.execution),
evidenceName(result.evidence));
std::printf("[sample] after the cancel: table exists %s, %d tables in the GeoPackage\n",
after->GetExists() ? "true" : "false", tables);
return (state.stoppedAt == 4 && state.total == 8 && cancelled &&
result.execution == GDK::glsTransferExecution::Cancelled &&
result.evidence == GDK::glsTransferEvidence::RolledBack && !after->GetExists() && tables == 3) ||
unexpected("expected a rolled back import");
}
결과와 경고
전송 서비스의 결과 객체(glsVectorTransferOutcome)는 다음을 담습니다.
| 항목 | 뜻 |
|---|---|
실행(glsTransferExecution) |
Completed(끝까지 확정), Rejected(쓰기 전에 거절), Cancelled(취소), Failed(실패). Export는 임시 자리에 쓰는 단계부터의 실패를 모두 Failed로 알립니다. 그 단계에서 하는 필드, 형식, 좌표계 검사에 걸려 아무것도 쓰지 않았을 때도 그렇습니다(근거 NotStarted). Rejected는 그 앞의 검사(빠진 인자, 파일 이름 하나가 아닌 Shapefile 레이어 이름, 원본일 수 있는 대상, 없는 폴더)와, 제자리로 옮기기 직전에 원본일 수 있는 대상을 한 번 더 확인하는 검사뿐입니다 |
근거(glsTransferEvidence) |
대상이 어떻게 되었는지. NotStarted(바뀌지 않음), RolledBack(쓴 것을 되돌림), Committed(확정), Unknown(알 수 없음), Partial(내보내기의 되돌리기가 일부만 됨) |
| 건수 | 쓴 피처 수, 변환 실패 건수. 취소되거나 실패한 결과의 건수는 되돌리기 전에 쓴 수입니다 |
| 콜백 실패 | 진행 콜백이 예외를 던졌는지 |
| 경고 | 결과를 되돌리지 않은 문제들의 문장(영어). 여러 문장이 이어 붙을 수 있고, 앞에 공백이 붙는 문장도 있습니다. 없으면 빈 문자열입니다 |
| 복구 보고서 | Export가 파일을 제자리로 옮기려 했을 때의 보고서 JSON(schemaVersion, state, error, warning, stagingDirectory, files의 output, backup, published, restored). 옮기기 전에 끝났거나 내보내기가 아니면 [] |
대상에 남은 것은 근거로 판단합니다. 진행 보고를 보고 짐작하지 마세요. 근거가 Unknown이거나 Partial이면 대상을 직접 확인하고, 자동으로 다시 시도하지 마세요. Import와 C++ Transfer에서 확정한 뒤의 마무리(예: 데이터셋 플러시)만 실패하면, 반환 상태는 실패이지만 실행은 Completed, 근거는 Committed이고 경고가 그 사실을 알립니다. Completed인 결과에서 대상이 M 값을 담지 못해 버린 경우 경고에 M values were dropped: the target layer cannot store them.이 붙습니다.
glsTransferExecution, glsTransferEvidence, glsTransferPhase의 값이 고정되어 있다는 약속은 없습니다(값이 고정된 열거형).
예제는 도로를 GeoJSON으로 다시 내보내면서 진행 콜백이 Complete에서 false를 돌려줍니다. 이미 게시가 끝났으므로 호출은 성공하고 Completed, Committed, 8건이며, 경고는 Progress callback failed or canceled after publication committed.이고 복구 보고서의 상태는 Committed입니다.
GetExecution, GetEvidence, GetFeatureCount, GetConversionFailureCount, GetCallbackFailed와, 두 번 부르는 문자열 규약(문자열)의 GetWarning, GetRecoveryJson으로 읽습니다.
// The outcome says how far the transfer got (execution), what happened to
// the target (evidence) and how many features were written; the warning
// collects what went wrong without undoing the result. A callback that asks
// to stop after the files were published cannot undo the export: the call
// succeeds and the warning says so. The recovery report lists the published
// files.
static bool outcome(GDK::glsDataSource& roads, const Paths& p)
{
std::vector<std::string> names;
std::vector<GDK::glsVectorTransferFieldMapping> fields;
if (!allFields(roads, names, fields)) {
return false;
}
GDK::glsVectorTransferOptions options;
options.TargetLayerName = "roads";
options.Fields = fields.data();
options.FieldCount = static_cast<int>(fields.size());
Result result;
const GDK::glsStatus called = exportLayer(roads, GDK::glsVectorExportFormat::GeoJson, p.folder / "roads.geojson",
options, stopWhenComplete, nullptr, result);
if (!reported(called, result)) {
return false;
}
const bool committedReport = result.recovery.find("\"state\":\"Committed\"") != std::string::npos;
std::printf("[sample] stop asked after publication: %s, %s, %" PRId64 " features\n",
executionName(result.execution), evidenceName(result.evidence), result.features);
std::printf("[sample] warning:%s\n", result.warning.c_str());
std::printf("[sample] recovery report says Committed: %s\n", committedReport ? "true" : "false");
return (result.execution == GDK::glsTransferExecution::Completed &&
result.evidence == GDK::glsTransferEvidence::Committed && result.features == 8 &&
result.warning == " Progress callback failed or canceled after publication committed." &&
committedReport) ||
unexpected("expected a committed export with a warning");
}
왕복했을 때 달라지는 값
예제는 내보낸 Shapefile을 다시 열어 name_ko의 한글 값 12개가 원본과 같은지, NULL이던 population 2건이 NULL이고 나머지 10건이 같은 값인지 확인합니다. 날짜는 FlatGeobuf로 내보냈다가 GeoPackage로 가져온 districts의 founded 5개가 원본(1802-05-14 등)과 같은 텍스트인지 확인합니다. 한글은 콘솔에 찍지 않고 값으로 비교합니다.
| 값 | Shapefile | GeoJSON | FlatGeobuf |
|---|---|---|---|
| 한글 문자열 | 같은 값(UTF-8, .cpg). 폭은 바이트 수이므로 값이 필드 폭을 넘으면 내보내기가 실패합니다 |
같은 값 | 같은 값 |
| NULL 정수 | NULL | NULL | NULL |
| NULL 불리언 | NULL | ||
빈 문자열 "" |
NULL이 됩니다 | ||
| 앞뒤 공백 | 지워집니다(" a " → "a") |
||
| 날짜 | 날짜 필드, 같은 값(yyyy-mm-dd) |
문자열 필드, 같은 텍스트 | 문자열 필드, 같은 텍스트 |
Time, DateTime, Binary |
담지 못함(NotSupported) |
Time은 문자열 필드 |
|
| 정수 | 폭 10 이상이면 Int64 필드로 읽힙니다(기본 계획의 GeoPackage 정수는 Int64(18)) |
형식 그대로. 다만 첫 피처의 값이 NULL이거나 모두 NULL이면 문자열 필드(실수와 불리언도 같음) | 형식 그대로 |
| 필드 이름 | 10바이트까지(필드 계획) | 그대로 | 그대로 |
| 좌표계 | 그대로 | EPSG:4326으로 바뀜 | 그대로 |
| M 값 | M 형식과 Z 형식의 파일만 담음(형식별 차이) | 버려짐(경고) | 담음 |
예제가 보여 주는 것은 Shapefile의 한글과 NULL 정수, FlatGeobuf를 거친 날짜입니다. GeoJSON과 FlatGeobuf의 한글과 NULL, NULL 불리언, 빈 문자열과 앞뒤 공백, Shapefile과 GeoJSON의 날짜는 예제가 보여 주지 않습니다. 빈 칸은 이 장이 설명하지 않는 칸입니다. Shapefile은 문자열 칸을 공백으로 채워 저장하고 읽을 때 앞뒤 공백을 지우므로, 빈 문자열과 공백만 있는 값은 NULL로 읽힙니다. 날짜는 yyyy-mm-dd 텍스트를 yyyymmdd로 저장했다가 읽을 때 되돌립니다.
// Values that went out and came back are compared with the original data:
// the Korean names and the NULL populations through the Shapefile, and the
// dates through FlatGeobuf and back into a GeoPackage.
static bool roundTripValues(const Paths& p)
{
DatasetPtr shp;
SourcePtr places;
if (!openReadOnly("shp://" + pathText(p.shapes), "places", shp, places)) {
return false;
}
int name = -1;
int nameKo = -1;
int population = -1;
if (!fieldIndex(*places, "name", name) || !fieldIndex(*places, "name_ko", nameKo) ||
!fieldIndex(*places, "population", population)) {
return false;
}
if (name < 0 || nameKo < 0 || population < 0) {
return unexpected("expected the fields name, name_ko and population");
}
int sameKo = 0;
int nulls = 0;
int sameNumber = 0;
GDK::glsFeatureCursor* rawCursor = nullptr;
if (!succeeded(places->GetFeatures(&rawCursor))) {
return false;
}
CursorPtr cursor(rawCursor);
for (;;) {
GDK::glsFeature feature;
bool has = false;
if (!succeeded(cursor->Next(&feature, &has))) {
return false;
}
if (!has) {
break;
}
GDK::glsAttributeValue n, ko, pop;
if (!succeeded(feature.GetAttribute(name, &n)) || !succeeded(feature.GetAttribute(nameKo, &ko)) ||
!succeeded(feature.GetAttribute(population, &pop))) {
return false;
}
const Place* expected = findPlace(stringOf(n));
if (expected == nullptr) {
continue;
}
sameKo += stringOf(ko) == expected->nameKo ? 1 : 0;
if (pop.Type == GDK::glsAttributeValueType::Null) {
nulls += expected->hasPopulation ? 0 : 1;
} else {
const int64_t value = pop.Type == GDK::glsAttributeValueType::Int64 ? pop.Int64Value : pop.Int32Value;
sameNumber += expected->hasPopulation && value == expected->population ? 1 : 0;
}
}
cursor.reset();
std::printf("[sample] Shapefile: name_ko equal %d of 12, population NULL %d, equal %d\n", sameKo, nulls,
sameNumber);
DatasetPtr gpkg;
SourcePtr districts;
if (!openReadOnly(p.imported, "districts", gpkg, districts)) {
return false;
}
int district = -1;
int founded = -1;
if (!fieldIndex(*districts, "district", district) || !fieldIndex(*districts, "founded", founded)) {
return false;
}
if (district < 0 || founded < 0) {
return unexpected("expected the fields district and founded");
}
int sameDate = 0;
std::string firstDate;
GDK::glsFeatureCursor* rawDates = nullptr;
if (!succeeded(districts->GetFeatures(&rawDates))) {
return false;
}
CursorPtr dates(rawDates);
for (;;) {
GDK::glsFeature feature;
bool has = false;
if (!succeeded(dates->Next(&feature, &has))) {
return false;
}
if (!has) {
break;
}
GDK::glsAttributeValue n, date;
if (!succeeded(feature.GetAttribute(district, &n)) || !succeeded(feature.GetAttribute(founded, &date))) {
return false;
}
const District* expected = findDistrict(stringOf(n));
if (expected != nullptr && stringOf(date) == expected->founded) {
++sameDate;
}
if (stringOf(n) == "Old Harbor") {
firstDate = stringOf(date);
}
}
std::printf("[sample] dates back in a GeoPackage: equal %d of 5 (Old Harbor %s)\n", sameDate, firstDate.c_str());
return (sameKo == 12 && nulls == 2 && sameNumber == 10 && sameDate == 5) ||
unexpected("expected the original values");
}
게시 도우미
Export가 쓰는 "임시 자리에 다 쓴 뒤 제자리로 옮기기"를 직접 쓸 수도 있습니다. 응용 프로그램이 파일을 스스로 만드는 경우(예: ExportToStaging이나 다른 쓰기 호출로 만든 파일을 게시할 때)에 씁니다.
glsExportPublication::Prepare(kind, outputPath, &plan)가 대상 폴더 안에 임시 폴더를 잡고 대상의 지금 상태를 기록합니다.kind는 파일 하나(SingleFile) 또는 Shapefile 묶음(ShapefileSet, 경로는.shp없는 이름)입니다.GetStagingPath가 파일을 쓸 자리를 줍니다.Commit()이 대상이 이미 있을 때의 3, 4단계를 합니다. 한 계획에서 한 번만 부를 수 있습니다.GetReportJson의state는NotStarted,Committed,RolledBack,RecoveryRequired이며,RecoveryRequired이면 자동으로 다시 시도하지 말고 보고서에 적힌 백업 파일을 보존합니다.CleanupStaging()은 계획이 만든 임시 파일만 지우고 백업은 지우지 않습니다. 계획을 반납할 때도 임시 폴더를 정리합니다.PrepareGeoPackage와CommitGeoPackage는 대상 자리가 비어 있을 때만 새 GeoPackage를 만들어 게시합니다. 이미 있는 파일을 바꾸지 않습니다.glsExportPlanService는 파일 이름에 쓸 수 없는 문자를 바꾸는SanitizeFileStem, Shapefile 묶음이 이미 있는지 보는ShapefileOutputExists, 여러 레이어를 한 폴더에 겹치지 않는 이름으로 내보낼 계획을 만드는BuildDirectoryPlan(JSON)을 제공합니다.glsVectorTransferService의ExportToStaging(C++만)은 게시 없이 주어진 데이터셋 URI에 내보내기만 하고, 게시는 호출자가 맡습니다.
C#에는 glsExportPublication(Prepare, PrepareGeoPackage, Commit, CommitGeoPackage, CleanupStaging, ReportJson 등, Dispose로 반납)과 glsExportPlanService(SanitizeFileStem, ShapefileOutputExists, BuildDirectoryPlan)가 있습니다. 자세한 내용은 C++ API 레퍼런스와 .NET API 레퍼런스를 보세요.
다음 장
가이드는 이 장으로 끝납니다. 각 형식과 함수의 자세한 설명은 C++ API 레퍼런스와 .NET API 레퍼런스에 있습니다. 처음부터 다시 보려면 1장 시작하기로 가세요.