본문으로 건너뛰기

피처 읽기와 질의

이 장은 벡터 데이터 소스에서 스키마를 읽고, 커서로 피처를 읽고, 조건을 걸어 질의하고, 속성 값을 꺼내고, 직접 편집하고, SQL을 실행하는 방법을 설명합니다. 데이터셋을 열고 데이터 소스를 여는 방법은 데이터셋에 있습니다. 지도와 연동되는 편집 워크플로는 10장 편집에서 다룹니다. 이 장의 편집은 데이터 소스에 바로 쓰는 방식입니다.

이 장의 코드는 sdk_samples의 features 예제에서 가져왔습니다. 예제는 예제 데이터 파일 harbor_town.gpkg의 places(점 12건)를 읽기 전용으로만 열어 읽고 질의하며, 쓰기는 임시 폴더에 복사한 파일에서 합니다. 실행할 때는 데이터 폴더를 첫 인자로 줍니다(<실행 파일> <sdk_samples/data 폴더>). 인자가 없거나 폴더가 없으면 사용법 한 줄을 출력하고 종료 코드 2로 끝납니다. 이 장은 시작하기의 호환성 확인과 공급자 등록이 끝났다고 가정합니다(초기화와 종료).

places의 필드는 name, name_ko(한글 이름), kind(harbor, market, school, park 중 하나, 값마다 3건), population입니다. population이 비어 있는(NULL) 장소가 2건 있습니다(sdk_samples/data의 README에도 같은 내용이 있습니다).

스키마

데이터 소스의 스키마는 glsFeatureDefn이고, 필드 하나하나는 glsFieldDefn입니다. 피처 정의와 필드 정의는 호출자가 소유하며 각자 반납합니다(소유권). 필드 번호는 0부터 시작하는 스키마 안의 순서이고, 질의 조건과 속성 읽기가 모두 이 번호를 씁니다. 이름으로 번호를 찾는 호출은 필드가 없으면 -1을 돌려줍니다(오류가 아닙니다).

glsDataSource::GetFeatureDefn이 glsFeatureDefn*을 돌려주고, glsReleaseFeatureDefn으로 반납합니다. glsFeatureDefn::GetField가 돌려주는 glsFieldDefn*은 glsReleaseFieldDefn으로 반납합니다. 이름은 두 번 호출하는 방식으로 읽습니다.

// The schema is a glsFeatureDefn; each field is a glsFieldDefn. Both are
// owned by the caller and released with their own release calls.
static bool readSchema(GDK::glsDataSource& source)
{
    GDK::glsFeatureDefn* rawDefn = nullptr;
    if (!source.GetFeatureDefn(&rawDefn).IsOk()) {
        std::printf("[sample] schema failed: %s\n", GDK::glsGetLastErrorMessage());
        return false;
    }
    DefnPtr defn(rawDefn, GDK::glsReleaseFeatureDefn);

    int count = 0;
    GDK::glsGeometryType geometryType = GDK::glsGeometryType::Point;
    if (!defn->GetFieldCount(&count).IsOk() || !defn->GetGeometryType(&geometryType).IsOk()) {
        std::printf("[sample] schema failed: %s\n", GDK::glsGetLastErrorMessage());
        return false;
    }
    std::printf("[sample] places: %d fields, geometry %s\n", count, geometryTypeName(geometryType));
    for (int i = 0; i < count; ++i) {
        GDK::glsFieldDefn* rawField = nullptr;
        if (!defn->GetField(i, &rawField).IsOk()) {
            std::printf("[sample] field %d failed: %s\n", i, GDK::glsGetLastErrorMessage());
            return false;
        }
        FieldPtr field(rawField, GDK::glsReleaseFieldDefn);
        const std::string name = sample::readString([&](char* buf, size_t size, size_t* required) {
            return field->GetName(buf, size, required);
        });
        GDK::glsFieldType type = GDK::glsFieldType::String;
        if (name.empty() || !field->GetFieldType(&type).IsOk()) {
            std::printf("[sample] field %d failed: %s\n", i, GDK::glsGetLastErrorMessage());
            return false;
        }
        std::printf("[sample] field %d: %s %s\n", i, name.c_str(), fieldTypeName(type));
    }
    return true;
}

이름으로 번호를 찾는 glsFeatureDefn::GetFieldIndex는 없는 이름이면 -1을 씁니다.

// A field's zero-based position in the schema, or -1 when there is no such
// field (that is a result, not an error). Query filters and attribute reads
// address fields by this index.
static int fieldIndex(GDK::glsDataSource& source, const char* name)
{
    GDK::glsFeatureDefn* raw = nullptr;
    if (!source.GetFeatureDefn(&raw).IsOk()) {
        return -1;
    }
    DefnPtr defn(raw, GDK::glsReleaseFeatureDefn);
    int index = -1;
    if (!defn->GetFieldIndex(name, &index).IsOk()) {
        return -1;
    }
    return index;
}

예제 데이터의 places를 읽으면 필드 3(population)의 형식이 Int64로 나옵니다. GeoPackage는 정수 열을 Int64로 알려 주므로, 필드 형식은 만들 때 지정한 값이 아니라 호출이 돌려주는 값을 기준으로 다루세요.

커서로 읽기

피처는 커서로 읽습니다. 커서는 질의가 여는 상태를 가지고 있고, 호출자가 소유합니다. 한 행을 읽을 때마다 Next를 부르고, 더 읽을 행이 없으면 Next는 끝났다고 알립니다. 끝은 오류가 아닙니다.

glsDataSource::GetFeatures가 glsFeatureCursor*를 돌려주고, glsReleaseFeatureCursor(또는 glsFeatureCursorDeleter)로 반납합니다. glsFeatureCursor::Next(glsFeature*, bool*)는 호출자가 가진 glsFeature에 행을 채웁니다. 행이 없으면 Ok 상태로 돌아오고 *outHasFeature가 false입니다. 한 glsFeature를 모든 행에 다시 써도 됩니다.

// Reads every feature with one cursor. Next() reports the end of the rows
// with *outHasFeature == false and an Ok status: that ends the loop and is not
// an error. One glsFeature is reused for every row.
static bool readAll(GDK::glsDataSource& source)
{
    GDK::glsFeatureCursor* raw = nullptr;
    if (!source.GetFeatures(&raw).IsOk()) {
        std::printf("[sample] read failed: %s\n", GDK::glsGetLastErrorMessage());
        return false;
    }
    CursorPtr cursor(raw);

    GDK::glsFeature feature;
    int count = 0;
    for (;;) {
        bool hasFeature = false;
        if (!cursor->Next(&feature, &hasFeature).IsOk()) {
            std::printf("[sample] read failed: %s\n", GDK::glsGetLastErrorMessage());
            return false;
        }
        if (!hasFeature) {
            break;
        }
        ++count;
    }
    std::printf("[sample] read all: %d features\n", count);
    return true;
}

커서는 Close로 공급자의 질의 자원을 일찍 놓을 수 있고, 공급자가 지원하면 Reset으로 처음으로 되돌릴 수 있습니다.

질의 조건

조건은 질의 구조체(C++ glsFeatureQuery)나 요청 객체(C# glsFeatureRequest)에 넣어 GetFeatures에 줍니다. 조건은 서로 함께 쓸 수 있습니다. 넣을 수 있는 것은 다음과 같습니다.

조건 C++ glsFeatureQuery C# glsFeatureRequest
공급자 SQL WHERE 조각 WhereClause WhereClause
속성 필터(필드 번호, 연산자, 값 문자열, 대소문자 구분) HasAttributeFilter, AttributeFilter SetAttributeFilter, ClearAttributeFilter
정렬(필드 번호, 오름/내림, NULL 위치. 번호 -1은 FID) HasAttributeOrderBy, AttributeOrderBy SetAttributeOrderBy, ClearAttributeOrderBy
건수 제한과 건너뛰기 Limit, Offset (0보다 작으면 없음) Limit, Offset (Nullable<Int64>, 0보다 작은 값을 넣어도 설정할 때는 오류가 없고, 요청을 쓰는 GetFeatures/CountFeatures가 ArgumentOutOfRangeException을 던짐)
읽을 필드 제한 SubsetAttributes, SubsetAttributeCount (비면 전체) SetSubsetAttributes, ClearSubsetAttributes (빈 배열이면 제한 해제)
지오메트리나 속성을 읽지 않기 NoGeometry, NoAttributes NoGeometry, NoAttributes
사각형 공간 필터(데이터 소스 CRS의 범위) HasSpatialFilter, SpatialFilter HasSpatialFilter, SpatialFilter
정확한 지오메트리 술어(Intersects, Contains) FilterGeometry, ExactIntersect, SpatialPredicate 없음
FID 목록 GetFeatures의 fids, fidCount 인자 AddFilterFid

NoAttributes가 true이면 FID와 지오메트리만 읽고 필드 부분집합은 무시됩니다. FilterGeometry를 주고 HasSpatialFilter를 false로 두면 DLL이 FilterGeometry에서 후보 범위를 만들고, 둘 다 주면 SpatialFilter가 후보 범위로 쓰입니다. 이 밖에 FID 이후부터 읽기와 정렬 기준 이후부터 읽기(C++ HasFidGreaterThan, HasKeysetAfter, C# SetFidGreaterThan, SetKeysetAfter)도 있습니다.

관리 래퍼에는 정확한 지오메트리 술어 조건이 없습니다. C# 요청에서 공간 조건은 SpatialFilter 범위 하나뿐입니다. 지오메트리끼리의 관계를 정확히 따져야 하면 범위로 후보를 줄인 뒤 C#에서 읽은 지오메트리에 glsGeometry.Intersects 같은 관계 메서드를 쓰세요.

빌려 주는 포인터의 수명

glsFeatureQuery는 안의 포인터를 모두 호출자에게서 빌립니다. 헤더는 이 포인터들이 그 구조체를 받는 호출이 진행되는 동안에만 쓰인다고 밝힙니다. WhereClause, AttributeFilter.Value, SubsetAttributes, FilterGeometry, 그리고 KeysetAfter.SortValue의 StringValue/BinaryData처럼 구조체 안의 포인터가 가리키는 대상은 GetFeatures(또는 GetFeatureCount)가 돌아올 때까지 살아 있어야 합니다. 임시 std::string의 c_str()을 구조체에 넣고 그 문자열을 먼저 없애지 마세요. 소유권 규칙은 소유권에 있습니다.

조건 질의

WHERE 조각은 공급자의 SQL 조건 그대로입니다. 예제는 kind = 'park'로 3건을 읽습니다.

// A WHERE clause is a provider SQL fragment. The query struct only borrows
// its pointers: the clause text must stay alive until GetFeatures returns.
static bool queryWhere(GDK::glsDataSource& source)
{
    const std::string clause = "kind = 'park'";
    GDK::glsFeatureQuery query;
    query.WhereClause = clause.c_str();

    GDK::glsFeatureCursor* raw = nullptr;
    if (!source.GetFeatures(&query, &raw).IsOk()) {
        std::printf("[sample] query failed: %s\n", GDK::glsGetLastErrorMessage());
        return false;
    }
    CursorPtr cursor(raw);

    GDK::glsFeature feature;
    std::string names;
    int count = 0;
    for (;;) {
        bool hasFeature = false;
        if (!cursor->Next(&feature, &hasFeature).IsOk()) {
            std::printf("[sample] query failed: %s\n", GDK::glsGetLastErrorMessage());
            return false;
        }
        if (!hasFeature) {
            break;
        }
        if (count > 0) {
            names += ", ";
        }
        names += textAt(feature, 0);
        ++count;
    }
    std::printf("[sample] where %s: %d features (%s)\n", clause.c_str(), count, names.c_str());
    return true;
}

속성 필터, 정렬, 건수 제한은 SQL 문자열 없이 멤버로 지정합니다. 예제는 population이 1000 이상인 장소 중 가장 큰 곳 하나를 읽습니다. 필터 값은 문자열로 줍니다.

// An attribute filter, a sort order and a row limit, set through struct
// members instead of SQL text. The filter value is passed as text.
static bool queryOrderLimit(GDK::glsDataSource& source)
{
    const int population = fieldIndex(source, "population");
    if (population < 0) {
        std::printf("[sample] no population field\n");
        return false;
    }

    GDK::glsFeatureQuery query;
    query.HasAttributeFilter = true;
    query.AttributeFilter.FieldIndex = population;
    query.AttributeFilter.Operator = GDK::glsAttributeFilterOperator::GreaterOrEqual;
    query.AttributeFilter.Value = "1000";
    query.HasAttributeOrderBy = true;
    query.AttributeOrderBy.FieldIndex = population;
    query.AttributeOrderBy.Ascending = false;
    query.Limit = 1;

    GDK::glsFeatureCursor* raw = nullptr;
    if (!source.GetFeatures(&query, &raw).IsOk()) {
        std::printf("[sample] query failed: %s\n", GDK::glsGetLastErrorMessage());
        return false;
    }
    CursorPtr cursor(raw);

    GDK::glsFeature feature;
    bool hasFeature = false;
    if (!cursor->Next(&feature, &hasFeature).IsOk() || !hasFeature) {
        std::printf("[sample] query failed: %s\n", GDK::glsGetLastErrorMessage());
        return false;
    }
    GDK::glsAttributeValue value;
    if (!feature.GetAttribute(population, &value).IsOk()) {
        std::printf("[sample] query failed: %s\n", GDK::glsGetLastErrorMessage());
        return false;
    }
    std::printf("[sample] largest place: %s (%" PRId64 ")\n", textAt(feature, 0).c_str(),
                integerOf(value));
    return true;
}

사각형 공간 질의

예제는 구역 Old Harbor의 지오메트리에서 범위를 읽고, 그 범위를 공간 필터로 places를 질의합니다. 이 데이터에서 결과는 2건(Lighthouse Pier, Fish Dock)입니다. 범위는 데이터 소스의 CRS 좌표여야 합니다.

glsFeature::GetGeometry는 지오메트리의 복사본을 돌려주므로 호출자가 glsReleaseGeometry로 반납합니다(예제는 glsGeometryDeleter를 쓰는 unique_ptr). 피처에 지오메트리가 없으면 Ok를 돌려주면서 포인터를 nullptr로 둡니다. 쓰기 전에 확인하세요(예제도 확인합니다).

// A rectangle filter: SpatialFilter is an envelope in the data source's CRS
// and is used when HasSpatialFilter is true. Here the rectangle is the
// envelope of one district, read from its geometry.
static bool querySpatial(GDK::glsDataset& dataset, GDK::glsDataSource& places)
{
    DataSourcePtr districts;
    if (!openSource(dataset, "districts", districts)) {
        return false;
    }

    GDK::glsEnvelope envelope;
    {
        GDK::glsFeatureQuery byName;
        byName.WhereClause = "name = 'Old Harbor'";
        GDK::glsFeatureCursor* raw = nullptr;
        if (!districts->GetFeatures(&byName, &raw).IsOk()) {
            std::printf("[sample] query failed: %s\n", GDK::glsGetLastErrorMessage());
            return false;
        }
        CursorPtr cursor(raw);
        GDK::glsFeature feature;
        bool hasFeature = false;
        if (!cursor->Next(&feature, &hasFeature).IsOk() || !hasFeature) {
            std::printf("[sample] district not found\n");
            return false;
        }
        // GetGeometry returns an owned copy, or leaves the pointer null (with an
        // Ok status) when the feature has no geometry.
        GDK::glsGeometry* rawGeometry = nullptr;
        if (!feature.GetGeometry(&rawGeometry).IsOk()) {
            std::printf("[sample] geometry failed: %s\n", GDK::glsGetLastErrorMessage());
            return false;
        }
        if (rawGeometry == nullptr) {
            std::printf("[sample] district has no geometry\n");
            return false;
        }
        GeometryPtr geometry(rawGeometry);
        if (!geometry->GetEnvelope(&envelope).IsOk()) {
            std::printf("[sample] envelope failed: %s\n", GDK::glsGetLastErrorMessage());
            return false;
        }
    }
    printEnvelope("Old Harbor envelope", envelope);

    GDK::glsFeatureQuery query;
    query.HasSpatialFilter = true;
    query.SpatialFilter = envelope;
    int64_t count = 0;
    if (!places.GetFeatureCount(&query, &count).IsOk()) {
        std::printf("[sample] count failed: %s\n", GDK::glsGetLastErrorMessage());
        return false;
    }
    std::printf("[sample] places in the envelope: %" PRId64 "\n", count);

    GDK::glsFeatureCursor* raw = nullptr;
    if (!places.GetFeatures(&query, &raw).IsOk()) {
        std::printf("[sample] query failed: %s\n", GDK::glsGetLastErrorMessage());
        return false;
    }
    CursorPtr cursor(raw);
    GDK::glsFeature feature;
    std::string names;
    for (;;) {
        bool hasFeature = false;
        if (!cursor->Next(&feature, &hasFeature).IsOk()) {
            std::printf("[sample] query failed: %s\n", GDK::glsGetLastErrorMessage());
            return false;
        }
        if (!hasFeature) {
            break;
        }
        if (!names.empty()) {
            names += ", ";
        }
        names += textAt(feature, 0);
    }
    std::printf("[sample] they are: %s\n", names.c_str());
    return true;
}

건수와 범위

개수만 필요하면 행을 읽는 대신 조건을 준 채 세기를 부르세요. 호출자는 행을 받지 않지만, 조건에 맞는 빠른 세기가 없는 공급자는 안에서 피처를 읽어 세므로 비쌀 수 있습니다. GetExtent(C#은 Extent())는 공급자가 알려 주는 레이어 범위를 데이터 소스의 CRS 좌표로 돌려줍니다. 공급자에 따라 저장된 범위를 돌려주기도 하고 그 자리에서 계산하기도 하므로 비쌀 수 있고, 범위를 모르면 호출은 성공하되 공급자마다 다른 자리표시 값(최소가 최대보다 큰 범위, 또는 모두 0)을 돌려줍니다. 실제 지오메트리의 범위가 필요하면 피처를 훑어 계산하는 ComputeFeatureExtent를 쓰세요.

GetFeatureCount는 조건 없이, 또는 glsFeatureQuery와 함께 부를 수 있습니다.

// Counting returns a number; the caller reads no rows. The extent is the
// provider's layer extent, in the data source CRS.
static bool countAndExtent(GDK::glsDataSource& source)
{
    int64_t all = 0;
    if (!source.GetFeatureCount(&all).IsOk()) {
        std::printf("[sample] count failed: %s\n", GDK::glsGetLastErrorMessage());
        return false;
    }
    std::printf("[sample] count: %" PRId64 "\n", all);

    GDK::glsFeatureQuery query;
    query.WhereClause = "kind = 'park'";
    int64_t parks = 0;
    if (!source.GetFeatureCount(&query, &parks).IsOk()) {
        std::printf("[sample] count failed: %s\n", GDK::glsGetLastErrorMessage());
        return false;
    }
    std::printf("[sample] count where kind = 'park': %" PRId64 "\n", parks);

    GDK::glsEnvelope extent;
    if (!source.GetExtent(&extent).IsOk()) {
        std::printf("[sample] extent failed: %s\n", GDK::glsGetLastErrorMessage());
        return false;
    }
    printEnvelope("extent", extent);
    return true;
}

FID로 하나 읽기

FID를 알면 질의 없이 한 건을 읽을 수 있습니다. 그 FID의 피처가 없으면 오류가 아니라 "없음"으로 알립니다.

glsDataSource::GetFeatureById는 Ok 상태로 돌아오고 *outFound가 false입니다.

// A lookup by FID reports "not found" with *outFound == false; that is not
// an error.
static bool readById(GDK::glsDataSource& source)
{
    const int64_t fids[] = {1, 9999};
    for (const int64_t fid : fids) {
        GDK::glsFeature feature;
        bool found = false;
        if (!source.GetFeatureById(fid, &feature, &found).IsOk()) {
            std::printf("[sample] lookup failed: %s\n", GDK::glsGetLastErrorMessage());
            return false;
        }
        if (found) {
            std::printf("[sample] feature %" PRId64 ": %s\n", fid, textAt(feature, 0).c_str());
        } else {
            std::printf("[sample] feature %" PRId64 ": not found\n", fid);
        }
    }
    return true;
}

0건과 실패

조건에 맞는 행이 없는 질의는 성공한 질의입니다. 실패와는 다르게 알립니다.

상황 C++ C#
맞는 행이 없음 GetFeatures와 Next가 Ok, 첫 Next에서 *outHasFeature가 false GetFeatures가 커서를 돌려주고 첫 Next()가 null
질의를 실행할 수 없음 (예: 없는 열을 쓴 WHERE 조각) 실패한 glsStatus (예제에서는 GetFeatures가 실패) 예외 (예제에서는 GetFeatures가 ArgumentException을 던짐)

예제는 kind = 'castle'(맞는 행이 없음)과 no_such_column = 1(실행할 수 없음)을 나란히 보여 줍니다. 위 표의 "실패"가 어느 호출에서 나타나는지는 질의에 따라 다를 수 있으므로 GetFeatures와 Next 양쪽의 결과를 확인하세요. C#에서 GetFeatures는 커서를 돌려주거나 예외를 던지고 null을 돌려주지 않습니다. 행이 끝났다는 신호는 Next()가 돌려주는 null 하나이며, 오류가 아닙니다(오류). (GetFeature(fid)의 null은 끝이 아니라 "그 FID의 피처가 없음"입니다.)

// "No rows" and "failed" are different. A query that matches nothing opens a
// cursor and the first Next() succeeds with *outHasFeature == false. A query
// that cannot run returns a failed status, from GetFeatures() or from Next().
static bool queryEmpty(GDK::glsDataSource& source)
{
    {
        GDK::glsFeatureQuery query;
        query.WhereClause = "kind = 'castle'";
        GDK::glsFeatureCursor* raw = nullptr;
        if (!source.GetFeatures(&query, &raw).IsOk()) {
            std::printf("[sample] query failed: %s\n", GDK::glsGetLastErrorMessage());
            return false;
        }
        CursorPtr cursor(raw);
        GDK::glsFeature feature;
        bool hasFeature = true;
        if (!cursor->Next(&feature, &hasFeature).IsOk() || hasFeature) {
            std::printf("[sample] expected an empty result\n");
            return false;
        }
        std::printf("[sample] no match: 0 features, the call succeeded\n");
    }
    {
        GDK::glsFeatureQuery query;
        query.WhereClause = "no_such_column = 1";
        GDK::glsFeatureCursor* raw = nullptr;
        bool failed = !source.GetFeatures(&query, &raw).IsOk();
        CursorPtr cursor(raw);
        if (!failed) {
            GDK::glsFeature feature;
            bool hasFeature = false;
            failed = !cursor->Next(&feature, &hasFeature).IsOk();
        }
        if (!failed) {
            std::printf("[sample] expected the query to fail\n");
            return false;
        }
        std::printf("[sample] bad where clause: the call failed\n");
    }
    return true;
}

값 읽기

피처의 속성은 필드 번호로 읽습니다. 값은 형식을 가지고 있습니다: Null, Boolean, Int32, Int64, Double, String, Binary. NULL은 형식이 Null인 값입니다.

glsFeature::GetAttribute(index, glsAttributeValue*)가 값을 채웁니다. glsAttributeValue는 Type과, 형식에 맞는 멤버(BoolValue, Int32Value, Int64Value, DoubleValue, StringValue, BinaryData와 BinarySize)를 가집니다.

StringValue와 BinaryData는 빌린 포인터입니다. 돌려받은 값에서는 그 값을 담고 있는 피처가 살아 있고 바뀌지 않는 동안에만 유효합니다. 같은 피처의 다른 속성을 읽는 것은 앞서 받은 포인터를 무효로 만들지 않습니다. 피처를 바꾸거나 없앤 뒤에도 필요하면 그 전에 바이트를 복사하세요(std::string으로 복사하는 것이 가장 쉽습니다). Next로 같은 glsFeature를 다시 채우는 것도 바꾸는 일이므로 복사는 그 전에 합니다. 일반 규칙은 문자열과 소유권에 있습니다.

glsFeature::GetGeometry는 지오메트리의 복사본을 돌려줍니다. 호출자가 소유하며 glsReleaseGeometry로 반납합니다. 피처에 지오메트리가 없으면 Ok를 돌려주면서 포인터를 nullptr로 두므로, 쓰기 전에 nullptr인지 확인하세요.

예제 데이터에서 population은 Int64로 읽히고, 값이 있는 10건의 합은 8100, NULL은 2건(East Quay, Hill Market)입니다. 예제는 Lighthouse Pier의 지오메트리를 WKT로 출력하기도 합니다.

// Reads attribute values by field index. A value has a Type; a NULL has type
// Null. String values point into the feature, so the text is copied before
// the feature changes. Korean text is compared by value, as UTF-8 bytes,
// instead of being printed.
static bool readValues(GDK::glsDataSource& source)
{
    const int name = fieldIndex(source, "name");
    const int nameKo = fieldIndex(source, "name_ko");
    const int population = fieldIndex(source, "population");
    if (name < 0 || nameKo < 0 || population < 0) {
        std::printf("[sample] a field is missing\n");
        return false;
    }

    GDK::glsFeatureCursor* raw = nullptr;
    if (!source.GetFeatures(&raw).IsOk()) {
        std::printf("[sample] read failed: %s\n", GDK::glsGetLastErrorMessage());
        return false;
    }
    CursorPtr cursor(raw);

    GDK::glsFeature feature;
    int withValue = 0;
    int withNull = 0;
    int64_t total = 0;
    bool typePrinted = false;
    bool utf8Checked = false;
    bool utf8Ok = false;
    std::string firstGeometry;
    for (;;) {
        bool hasFeature = false;
        if (!cursor->Next(&feature, &hasFeature).IsOk()) {
            std::printf("[sample] read failed: %s\n", GDK::glsGetLastErrorMessage());
            return false;
        }
        if (!hasFeature) {
            break;
        }
        const std::string placeName = textAt(feature, name);

        GDK::glsAttributeValue value;
        if (!feature.GetAttribute(population, &value).IsOk()) {
            std::printf("[sample] read failed: %s\n", GDK::glsGetLastErrorMessage());
            return false;
        }
        if (value.Type == GDK::glsAttributeValueType::Null) {
            std::printf("[sample] NULL population: %s\n", placeName.c_str());
            ++withNull;
        } else {
            if (!typePrinted) {
                std::printf("[sample] population value type: %s\n", valueTypeName(value.Type));
                typePrinted = true;
            }
            total += integerOf(value);
            ++withValue;
        }

        if (placeName == "Lighthouse Pier") {
            utf8Checked = true;
            utf8Ok = textAt(feature, nameKo) == "등대 부두";

            GDK::glsGeometry* rawGeometry = nullptr;
            if (!feature.GetGeometry(&rawGeometry).IsOk()) {
                std::printf("[sample] geometry failed: %s\n", GDK::glsGetLastErrorMessage());
                return false;
            }
            if (rawGeometry == nullptr) {
                firstGeometry = "(no geometry)";
            } else {
                GeometryPtr geometry(rawGeometry);
                firstGeometry = sample::readString([&](char* buf, size_t size, size_t* required) {
                    return geometry->ToWkt(buf, size, required);
                });
            }
        }
    }
    std::printf("[sample] population: %d values, %d NULL, total %" PRId64 "\n", withValue, withNull,
                total);
    std::printf("[sample] Lighthouse Pier geometry: %s\n", firstGeometry.c_str());
    if (!utf8Checked || !utf8Ok) {
        std::printf("[sample] utf8 check failed\n");
        return false;
    }
    std::printf("[sample] utf8 ok\n");
    return true;
}

한글 값

문자열은 UTF-8이고, C#에서는 .NET 문자열(UTF-16)로 바뀌어 도착합니다. 예제는 name_ko의 한글 값을 콘솔에 찍지 않고 기대하는 문자열과 값으로 비교한 뒤 utf8 ok를 출력합니다. C++ 예제는 소스 파일을 UTF-8로 저장하고 MSVC에 /utf-8 옵션을 줍니다(예제의 CMake 설정).

직접 편집과 트랜잭션

데이터 소스에는 AddFeature, UpdateFeature, DeleteFeature로 피처를 직접 쓸 수 있습니다. 이 장의 편집은 데이터 소스에 바로 쓰는 방식이고, 지도와 연동되는 편집 워크플로는 10장 편집에서 다룹니다(두 방식의 차이는 직접 쓰기와의 차이). 여러 쓰기를 한꺼번에 확정하거나 되돌리려면 데이터셋에서 트랜잭션을 시작합니다. 트랜잭션은 Commit() 또는 Rollback()으로 끝낸 뒤에 반납하세요. Commit()이 실패했을 때는 IsActive로 트랜잭션이 아직 활성인지 확인하고, 활성이면 Rollback()으로 끝냅니다(예제가 이렇게 합니다).

쓰기가 가능하게 여는 파일은 열기에서 설명한 대로 WAL 방식으로 바뀌므로, 예제 데이터는 쓰기로 열지 않고 임시 폴더에 복사한 파일에서 편집합니다. 복사는 SDK가 아니라 표준 라이브러리(C++ std::filesystem::copy_file, C# File.Copy)로 합니다. 복사본은 원본의 읽기 전용 특성을 그대로 가지므로, 예제는 복사본의 읽기 전용 특성을 지운 뒤에 엽니다(원본이 읽기 전용 폴더나 매체에 있어도 편집과 정리가 됩니다). 편집이 끝나면 복사본의 데이터셋과 데이터 소스를 모두 반납한 다음 임시 폴더를 지웁니다. 열린 파일은 Windows에서 지울 수 없습니다.

AddFeature, UpdateFeature에 주는 const glsFeature*는 호출 동안만 빌립니다. glsFeature::SetAttribute는 받은 값을 복사하므로 문자열은 호출이 끝날 때까지만 살아 있으면 됩니다. 지오메트리는 WKB 바이트와 SRID로 줍니다(SetGeometryFromWkbWithSrid). 쓰기 호출은 glsStatus를 돌려줍니다.

// Builds a feature to insert. SetAttribute copies the value it is given, so
// the strings only need to live through the call. The geometry goes in as WKB
// bytes with its SRID.
static bool buildFeature(GDK::glsFeature& feature, const char* name, int population, double x,
                         double y)
{
    GDK::glsAttributeValue text;
    text.Type = GDK::glsAttributeValueType::String;
    text.StringValue = name;
    GDK::glsAttributeValue kind;
    kind.Type = GDK::glsAttributeValueType::String;
    kind.StringValue = "harbor";
    GDK::glsAttributeValue count;
    count.Type = GDK::glsAttributeValueType::Int32;
    count.Int32Value = population;
    if (!feature.SetAttribute(0, &text).IsOk() || !feature.SetAttribute(1, &text).IsOk() ||
        !feature.SetAttribute(2, &kind).IsOk() || !feature.SetAttribute(3, &count).IsOk()) {
        return false;
    }

    GDK::glsGeometry* raw = nullptr;
    if (!GDK::glsGeometryCreatePoint(x, y, 4326, &raw).IsOk()) {
        return false;
    }
    GeometryPtr geometry(raw);
    size_t size = 0;
    if (!geometry->ToWkb(nullptr, 0, &size).IsOk()) {
        return false;
    }
    std::vector<uint8_t> wkb(size);
    if (!geometry->ToWkb(wkb.data(), wkb.size(), &size).IsOk()) {
        return false;
    }
    return feature.SetGeometryFromWkbWithSrid(wkb.data(), size, 4326).IsOk();
}

glsDataset::BeginTransaction이 돌려주는 glsTransaction*은 glsReleaseTransaction으로 반납합니다. 예제는 트랜잭션 안에서 추가해 확정하고, 직접 수정하고, 트랜잭션 안에서 삭제한 것을 되돌리고, 마지막으로 직접 삭제합니다. 각 단계 뒤에 건수를 출력합니다.

// Direct edits: AddFeature, UpdateFeature and DeleteFeature write to the data
// source directly. BeginTransaction groups writes so that they are committed
// or undone together. End every transaction with Commit() or Rollback().
static bool editRecords(GDK::glsDataset& dataset, GDK::glsDataSource& places)
{
    // 1. Add inside a transaction and commit.
    {
        GDK::glsTransaction* rawTx = nullptr;
        if (!dataset.BeginTransaction(&rawTx).IsOk()) {
            std::printf("[sample] begin failed: %s\n", GDK::glsGetLastErrorMessage());
            return false;
        }
        TransactionPtr tx(rawTx, GDK::glsReleaseTransaction);
        GDK::glsFeature feature;
        if (!buildFeature(feature, "Test Pier", 100, 10.095, 50.059) ||
            !places.AddFeature(&feature).IsOk()) {
            std::printf("[sample] add failed: %s\n", GDK::glsGetLastErrorMessage());
            tx->Rollback();
            return false;
        }
        if (!tx->Commit().IsOk()) {
            std::printf("[sample] commit failed: %s\n", GDK::glsGetLastErrorMessage());
            // A failed commit may leave the transaction active: end it.
            bool active = false;
            if (tx->IsActive(&active).IsOk() && active) {
                tx->Rollback();
            }
            return false;
        }
    }
    if (!reportCount(places, "after commit of the add", 13)) {
        return false;
    }

    // Find the new feature's FID: AddFeature does not report it.
    int64_t fid = -1;
    {
        GDK::glsFeatureQuery query;
        query.WhereClause = "name = 'Test Pier'";
        GDK::glsFeatureCursor* raw = nullptr;
        if (!places.GetFeatures(&query, &raw).IsOk()) {
            std::printf("[sample] query failed: %s\n", GDK::glsGetLastErrorMessage());
            return false;
        }
        CursorPtr cursor(raw);
        GDK::glsFeature feature;
        bool hasFeature = false;
        if (!cursor->Next(&feature, &hasFeature).IsOk() || !hasFeature ||
            !feature.GetId(&fid).IsOk()) {
            std::printf("[sample] new feature not found\n");
            return false;
        }
    }

    // 2. Update directly: read the feature, change a value, write it back.
    {
        GDK::glsFeature feature;
        bool found = false;
        if (!places.GetFeatureById(fid, &feature, &found).IsOk() || !found) {
            std::printf("[sample] lookup failed\n");
            return false;
        }
        GDK::glsAttributeValue count;
        count.Type = GDK::glsAttributeValueType::Int32;
        count.Int32Value = 2000;
        if (!feature.SetAttribute(3, &count).IsOk() || !places.UpdateFeature(&feature).IsOk()) {
            std::printf("[sample] update failed: %s\n", GDK::glsGetLastErrorMessage());
            return false;
        }
    }
    {
        GDK::glsFeature feature;
        bool found = false;
        GDK::glsAttributeValue value;
        if (!places.GetFeatureById(fid, &feature, &found).IsOk() || !found ||
            !feature.GetAttribute(3, &value).IsOk()) {
            std::printf("[sample] lookup failed\n");
            return false;
        }
        std::printf("[sample] after update: population %" PRId64 "\n", integerOf(value));
    }

    // 3. Delete inside a transaction and roll it back.
    {
        GDK::glsTransaction* rawTx = nullptr;
        if (!dataset.BeginTransaction(&rawTx).IsOk()) {
            std::printf("[sample] begin failed: %s\n", GDK::glsGetLastErrorMessage());
            return false;
        }
        TransactionPtr tx(rawTx, GDK::glsReleaseTransaction);
        if (!places.DeleteFeature(fid).IsOk()) {
            std::printf("[sample] delete failed: %s\n", GDK::glsGetLastErrorMessage());
            tx->Rollback();
            return false;
        }
        if (!tx->Rollback().IsOk()) {
            std::printf("[sample] rollback failed: %s\n", GDK::glsGetLastErrorMessage());
            return false;
        }
    }
    if (!reportCount(places, "after rollback of the delete", 13)) {
        return false;
    }

    // 4. Delete directly.
    if (!places.DeleteFeature(fid).IsOk()) {
        std::printf("[sample] delete failed: %s\n", GDK::glsGetLastErrorMessage());
        return false;
    }
    return reportCount(places, "after the direct delete", 12);
}
// Edits never touch the shipped file. The file is copied into a temporary
// folder with the standard library, opened writable there, and the folder is
// removed at the end, after every handle on the copy is released.
static bool editCopy(const std::filesystem::path& shipped)
{
    const std::string folder = sample::tempDir("features");
    if (folder.empty()) {
        std::printf("[sample] cannot create a temporary folder\n");
        return false;
    }
    bool ok = false;
    {
        const std::filesystem::path copy = std::filesystem::path(folder) / "harbor_town.gpkg";
        std::error_code ec;
        bool copied = std::filesystem::copy_file(shipped, copy,
                                                 std::filesystem::copy_options::overwrite_existing, ec);
        // The copy keeps the source's read-only attribute; clear it so the copy
        // opens writable and the folder can be removed afterwards.
        if (copied) {
            std::filesystem::permissions(copy, std::filesystem::perms::owner_write,
                                         std::filesystem::perm_options::add, ec);
            copied = !ec;
        }
        if (!copied) {
            std::printf("[sample] copy failed\n");
        } else {
            const std::string uri = gpkgUri(copy);
            GDK::glsDataset* raw = nullptr;
            if (!GDK::glsOpenDataset(uri.c_str(), &raw).IsOk()) {
                std::printf("[sample] open failed: %s\n", GDK::glsGetLastErrorMessage());
            } else {
                DatasetPtr dataset(raw);
                DataSourcePtr places;
                ok = openSource(*dataset, "places", places) && editRecords(*dataset, *places);
            }
        }
    }
    // The copy's dataset and data source are released above.
    sample::removeDir(folder);
    std::error_code gone;
    if (std::filesystem::exists(folder, gone)) {
        std::printf("[sample] the temporary folder was not removed\n");
        ok = false;
    }
    return ok;
}

SQL 실행

데이터셋의 SQL 실행기로 SQL을 직접 실행할 수 있습니다. 예제는 읽기 전용으로 연 데이터셋에서 SELECT를 한 번 실행합니다. 이때 파일 옆에 부수 파일이 생기지 않고 파일도 바뀌지 않습니다. 실행기와 커서는 호출자가 소유하며 각각 반납합니다(예제는 커서를 먼저, 실행기를 그다음에 반납합니다).

glsDataset::CreateSqlExecutor가 glsSqlExecutor*를 돌려주고, glsSqlExecutor::ExecuteQuery가 glsSqlCursor*를 돌려줍니다. 각각 glsReleaseSqlExecutor, glsReleaseSqlCursor로 반납합니다. 열 정보는 첫 Next 전에 읽을 수 있습니다. GetValue가 돌려주는 문자열 같은 포인터는 다음 Next나 Close까지만 유효하므로 바로 쓰거나 복사하세요.

// Raw SQL goes through the dataset's SQL executor. The text of a value is
// borrowed until the next Next() or Close(), so it is printed (or copied) at
// once.
static bool runSql(GDK::glsDataset& dataset)
{
    GDK::glsSqlExecutor* rawExecutor = nullptr;
    if (!dataset.CreateSqlExecutor(&rawExecutor).IsOk()) {
        std::printf("[sample] sql failed: %s\n", GDK::glsGetLastErrorMessage());
        return false;
    }
    ExecutorPtr executor(rawExecutor, GDK::glsReleaseSqlExecutor);

    GDK::glsSqlCursor* rawCursor = nullptr;
    if (!executor->ExecuteQuery("SELECT kind, COUNT(*) AS n FROM places GROUP BY kind ORDER BY kind",
                                &rawCursor).IsOk()) {
        std::printf("[sample] sql failed: %s\n", GDK::glsGetLastErrorMessage());
        return false;
    }
    SqlCursorPtr cursor(rawCursor, GDK::glsReleaseSqlCursor);

    int columns = 0;
    if (!cursor->GetColumnCount(&columns).IsOk() || columns != 2) {
        std::printf("[sample] sql failed: %s\n", GDK::glsGetLastErrorMessage());
        return false;
    }
    std::string header;
    for (int i = 0; i < columns; ++i) {
        const std::string column = sample::readString([&](char* buf, size_t size, size_t* required) {
            return cursor->GetColumnName(i, buf, size, required);
        });
        header += (i > 0 ? " " : "") + column;
    }
    std::printf("[sample] sql columns: %s\n", header.c_str());

    for (;;) {
        bool hasRow = false;
        if (!cursor->Next(&hasRow).IsOk()) {
            std::printf("[sample] sql failed: %s\n", GDK::glsGetLastErrorMessage());
            return false;
        }
        if (!hasRow) {
            break;
        }
        GDK::glsAttributeValue kind;
        GDK::glsAttributeValue count;
        if (!cursor->GetValue(0, &kind).IsOk() || !cursor->GetValue(1, &count).IsOk()) {
            std::printf("[sample] sql failed: %s\n", GDK::glsGetLastErrorMessage());
            return false;
        }
        std::printf("[sample] sql row: %s %" PRId64 "\n", stringOf(kind).c_str(), integerOf(count));
    }
    return true;
}

데이터를 바꾸는 SQL은 쓰기로 연 데이터셋에서 실행해야 하며 이 장에서는 다루지 않습니다.

이 장에서 쓴 형식과 멤버의 자세한 설명은 C++ API 레퍼런스와 .NET API 레퍼런스에 있습니다.

다음 장

다음 장 지오메트리와 좌표계에서는 지오메트리를 WKT와 WKB로 다루는 방법, 공간 관계와 연산, 좌표계와 좌표 변환을 다룹니다. 피처를 읽는 방법과 소유권 규칙은 이 장과 공통 규약에 있습니다.

관련 .NET API

.NET 시작하기 · 객체 관계와 처리 흐름