From 75faec96a742ae8e2a4145708d8777d11a95c1dc Mon Sep 17 00:00:00 2001 From: Alexander Lowey-Weber Date: Tue, 25 Aug 2026 17:17:54 +0200 Subject: [PATCH 01/41] Fix numeric id queries using the new member query option. Signed-off-by: Alexander Lowey-Weber --- .../naksha/model/request/ReadFeatures.kt | 85 ++++++++++++++----- .../kotlin/naksha/model/request/ops/Op.kt | 26 ++++++ .../kotlin/naksha/psql/PgQueryWhereBuilder.kt | 50 ++++++----- .../kotlin/naksha/psql/InsertFeatureTest.kt | 17 ++++ 4 files changed, 138 insertions(+), 40 deletions(-) diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/ReadFeatures.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/ReadFeatures.kt index 4dba6f034..39704c851 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/ReadFeatures.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/ReadFeatures.kt @@ -19,9 +19,11 @@ import kotlin.math.max /** * Read features from a collection of a map of a storage. * - * If a logical **OR** between the different condition is needed, for example search for features being in a certain bounding box **or** having a certain tag, then two read-requests should be executed, and joined by the client. These queries can be executed in parallel using two distinct sessions to improve the performance. + * The correct way to search is to use [queryMembers]. The given query is limited based upon some additional arguments. If deleted states are wanted, set [queryDeleted] to _true_, otherwise the query engine will ignore all states that are in [DELETE][naksha.base.Action.DELETE] state. * - * @since 3.0.0 + * However, + * + * @since 3.0 */ @JsExport open class ReadFeatures : ReadRequest() { @@ -119,24 +121,32 @@ open class ReadFeatures : ReadRequest() { /** * Extend the request to include features that are in a deleted state _(defaults to `false`)_. + * + * - If this query-option is `true` and all states of feature, including the tombstones _(soft-deletes)_ will be added to the result-set. + * - If the query-option is `false` and the latest state of a feature is [DELETE][naksha.base.Action.DELETE], all states of this feature are excluded from the result-set. + * + * **Beware**: The decision is based only upon the latest returned state, even when requesting multiple [versions] from the storage. + * @since 3.0 */ var queryDeleted: Boolean by BOOLEAN_OR_FALSE /** * Extend the request to search through historic states of features _(defaults to `false`)_. * - * Setting this to `true` adds past states from the **HISTORY** section to the result set. When [versions] is greater than `1`, results are ordered automatically by the storage in reverse version order, so the most recent state is returned first. + * - If this query-option is `true` all states of matching features that are in the given version range, so between [minVersion] and [version], are added to the result set. When [versions] is greater than `1`, results are returned in reverse version order, so the most recent state is returned first. This makes seeking through the result easier _(and the application of [queryDeleted])_. + * - If this query-option is `false`, the set version limits via [minVersion] and [version] do only apply to the latest state of a feature. Therefore, even when multiple [versions] are requested, only one state will be returned, because only the latest state is searched. If the latest state is outside the defined version range, so not between [minVersion] and [version], the feature is excluded from the result-set. + * @since 3.0 */ var queryHistory: Boolean by BOOLEAN_OR_FALSE /** - * Defines how many states (versions) of each matching feature should be returned _(defaults to `1`)_. + * Defines how many states _(versions)_ of each matching feature should be returned _(defaults to `1`)_. * - * - A value of `1` _(the default)_ means only the single latest state closest to the given maximal [version] is returned. + * - A value of `1` _(the default)_ means only the single state, closest to the given maximal [version], is returned. * - If the underlying JSON map contains a values that is not a number or invalid, the default value `1` will be used. * * Requesting multiple versions can have a significant performance impact and should be used with care. - * @since 3.0.0 + * @since 3.0 */ var versions: Int get() { @@ -154,7 +164,7 @@ open class ReadFeatures : ReadRequest() { * Limit the read to all states at or after the given minimum version, `null` if no limit. * * If the underlying JSON map contains a values that is not a number or invalid, the default value `null` will be used. - * @since 3.0.0 + * @since 3.0 */ var minVersion: Int64? get() { @@ -173,18 +183,27 @@ open class ReadFeatures : ReadRequest() { set("minVersion", value) } + /** + * @see minVersion + */ @JsName("withMinVersionInt64") fun withMinVersion(minVersion: Int64?): ReadFeatures { this.minVersion = minVersion return this } + /** + * @see minVersion + */ @JsName("withMinVersion") fun withMinVersion(minVersion: Version?): ReadFeatures { this.minVersion = minVersion?.number return this } + /** + * @see minVersion + */ @JsName("withMinVersionLong") fun withMinVersion(minVersion: Long?): ReadFeatures { this.minVersion = if (minVersion != null) Int64(minVersion) else null @@ -192,12 +211,12 @@ open class ReadFeatures : ReadRequest() { } /** - * Limit the read to states at or before the given maximum version, `null` if no limit _([HEAD][Version.VersionCompanion.HEAD])_. + * Limit the read to states at or before the given maximum version, `null` if no limit _(read up to [HEAD][Version.VersionCompanion.HEAD] aka up until latest state)_. * - * This effectively requests a specific historical snapshot, when no [minVersion] is set and [versions] is `1`, which is the default for both parameters. + * This effectively requests a specific historical snapshot when no [minVersion] is set and [versions] is `1`, which is the default for both parameters. * * If the underlying JSON map contains a values that is not a number or invalid, the default value `null` will be used. - * @since 3.0.0 + * @since 3.0 */ var version: Int64? get() { @@ -210,18 +229,27 @@ open class ReadFeatures : ReadRequest() { set("version", value) } + /** + * @see version + */ @JsName("withVersionInt64") fun withVersion(version: Int64?): ReadFeatures { this.version = version return this } + /** + * @see version + */ @JsName("withVersion") fun withVersion(version: Version?): ReadFeatures { this.version = version?.number return this } + /** + * @see version + */ @JsName("withVersionLong") fun withVersion(version: Long?): ReadFeatures { this.version = if (version != null) Int64(version) else null @@ -233,39 +261,53 @@ open class ReadFeatures : ReadRequest() { * Order the result-set like given; this is an expensive operation and should be avoided. * * If an order is required, but no specific one, then it is strongly recommended to stick with the [deterministic order][OrderBy.deterministic], which is produced by creating a blank empty [OrderBy] object or through the static helper method [OrderBy.deterministic]. Ordering by anything else can have a drastic performance impact. + * @since 3.0 */ var orderBy: OrderBy? by ORDER_BY_OR_NULL /** * Add all features that match the given IDs into the result-set. - * @since 3.0.0 + * + * **This query-option is ignored when [queryMembers] is not `null`!** + * @since 3.0 + * @see queryMembers */ - @Deprecated("Replaced with op", replaceWith = ReplaceWith("op")) + @Deprecated("Replaced with queryMembers.", replaceWith = ReplaceWith("queryMembers")) var featureIds: StringList by STRING_LIST /** * Add all features that match the given [GUIDs][naksha.base.Guid] into the result-set. * - * This can be used to load features in specific states. - * @since 3.0.0 + * **This query-option is ignored when [queryMembers] is not `null`!** + * + * **This query-option is deprecated, please use [ISession.loadTuples][naksha.model.ISession.loadTuples] for this purpose.** + * + * As long as the requested features are in the same collection that the [ReadFeatures] address _([collectionId])_, and [queryMembers] is `null`, there is downward compatibility code that translates this into a match against the virtual members [FeatureNumber][naksha.model.objects.StandardMembers.FeatureNumber] and [FeatureVersion][naksha.model.objects.StandardMembers.FeatureVersion]. + * + * @since 3.0 + * @see naksha.model.ISession.loadTuples */ - // TODO: We should replace this with `tupleNumbers`, because that is what we will encode into `uuid` and that is what the clients need. - // Is there any use-case for the GUID any longer? - @Deprecated("Replace with load by tuple-number, should not be part of the query!", replaceWith = ReplaceWith("op")) + @Deprecated("Replace with ISession.loadTuples or queryMembers, if the tuples are located in the same collection.") var guids: GuidList by GUID_LIST /** * Add all features that match the given query into the result-set. - * @since 3.0.0 + * + * **This query-option is ignored when [queryMembers] is not `null`!** + * @since 3.0 + * @see queryMembers */ - @Deprecated("Replaced with op", replaceWith = ReplaceWith("op")) + @Deprecated("Replaced with queryMembers.", replaceWith = ReplaceWith("queryMembers")) var query: RequestQuery by QUERY /** - * The [operations][Op] to execute to query members. + * The query [operations][Op] to execute to against [members][naksha.model.objects.Member] to find features. + * + * This new query option is much more flexible than the previous deprecated one. * - * This replaces [query] and must not be used together with [query]. It actually allows to query for any member value. In doubt, [queryMembers] always wins. + * This option replaces [featureIds], [guids], and [query] and must not be used together with any of them. If [queryMembers] is provided, the query engine does not support the deprecated old query-options [featureIds], [guids], and [query]. If any of the deprecated options is used together with [queryMembers], the engine will throw [NakshaException][naksha.base.NakshaException] with error [ILLEGAL_ARGUMENT][naksha.base.NakshaError.ILLEGAL_ARGUMENT]; it is not possible to combine the old and new query options! * @since 3.0 + * @see Op */ var queryMembers: Op? by OP_OR_NULL @@ -277,6 +319,7 @@ open class ReadFeatures : ReadRequest() { * The method ignores an optionally provided [ordering][orderBy]. * @return `true` if the query is effectively reading all current HEAD states of all features; * `false` otherwise. + * @since 3.0 */ fun isReadAllFromHead(): Boolean = minVersion == null && !queryDeleted diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/ops/Op.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/ops/Op.kt index 0cd9053af..a4e0e1967 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/ops/Op.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/ops/Op.kt @@ -15,6 +15,32 @@ import kotlin.jvm.JvmStatic /** * A member operation. * @since 3.0 + * @see And + * @see Equals + * @see Gt + * @see Gte + * @see Intersects + * @see IsAnyOf + * @see IsFalse + * @see IsNull + * @see IsTrue + * @see Lt + * @see Lte + * @see Not + * @see Or + * @see StartsWith + * @see TagEquals + * @see TagGt + * @see TagGte + * @see TagIsNull + * @see TagListContains + * @see TagListContainsAllOf + * @see TagListContainsAnyOf + * @see TagMapHasAllOf + * @see TagMapHasAnyOf + * @see TagMapHasKey + * @see TagMatches + * @see TagStartsWith */ @JsExport open class Op : AnyObject() { diff --git a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgQueryWhereBuilder.kt b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgQueryWhereBuilder.kt index 03f89a7be..31524a084 100644 --- a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgQueryWhereBuilder.kt +++ b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgQueryWhereBuilder.kt @@ -35,15 +35,25 @@ internal class PgQueryWhereBuilder(private val request: ReadFeatures, private va */ fun build(): PgQueryWhereClause? { var op: Op? = request.queryMembers - if (op == null) op = QueryConverter.convert(request.query) - // Only read everything when there is no filter at all — featureIds/guids apply even when op is null. - if (op == null && request.featureIds.isEmpty() && request.guids.isEmpty()) return null - if (op != null) applyOp(op) - if (request.featureIds.isNotEmpty()) { // TODO backward compatibility for feature IDs read requests, to be removed - whereFeatureId() - } - if (request.guids.isNotEmpty()) { // TODO backward compatibility for GUIDs read requests, remove if nowhere else is using it - whereGuids() + if (op == null) { + // Note: ReadFeatures clearly states, that `queryMembers` always wins, so we only recognize if op is null! + op = QueryConverter.convert(request.query) + // Only read everything when there is no filter at all — featureIds/guids apply even when op is null. + if (op == null && request.featureIds.isEmpty() && request.guids.isEmpty()) return null + if (request.featureIds.isNotEmpty()) { // TODO backward compatibility for feature IDs read requests, to be removed + whereFeatureId() + } + if (request.guids.isNotEmpty()) { // TODO backward compatibility for GUIDs read requests, remove if nowhere else is using it + whereGuids() + } + } else { + if (request.query.isNotEmpty()) + throw illegalArg("Old 'query' option must not be combined with new 'queryMember'") + if (request.featureIds.isNotEmpty()) + throw illegalArg("Old 'featureIds' option must not be combined with new 'queryMember'") + if (request.guids.isNotEmpty()) + throw illegalArg("Old 'guids' option must not be combined with new 'queryMember'") + applyOp(op) } return PgQueryWhereClause(collection, where.toString(), argValues, argTypes) } @@ -169,11 +179,11 @@ internal class PgQueryWhereBuilder(private val request: ReadFeatures, private va } is TagMapHasAnyOf -> { if (negate) where.append("NOT ") - where.append(at).append("::jsonb").append(" ??| ").append(placeholderForArg(op.tagKeys, PgType.STRING_ARRAY)).append(" ") + where.append(at).append("::jsonb").append(" ??| ").append(placeholderForArg(op.tagKeys)).append(" ") } is TagMapHasAllOf -> { if (negate) where.append("NOT ") - where.append(at).append("::jsonb").append(" ??& ").append(placeholderForArg(op.tagKeys, PgType.STRING_ARRAY)).append(" ") + where.append(at).append("::jsonb").append(" ??& ").append(placeholderForArg(op.tagKeys)).append(" ") } is TagIsNull -> { // ( foo::jsonb ? $1 AND ((foo::jsonb)->>$1) IS [NOT ]NULL) @@ -188,7 +198,7 @@ internal class PgQueryWhereBuilder(private val request: ReadFeatures, private va if (negate) where.append("NOT ") // [NOT ]((foo::jsonb)->>$1)::int8 = $2 where.append("((").append(at).append("::jsonb)") - .append("->>").append(placeholderForArg(op.key)).append(")::").append(pgType) + .append("->>").append(placeholderForArg(op.key)).append("::").append(pgType).append(")") .append("=").append(placeholderForArg(value, pgType)) } is TagGt -> { @@ -197,7 +207,7 @@ internal class PgQueryWhereBuilder(private val request: ReadFeatures, private va if (negate) where.append("NOT ") // [NOT ]((foo::jsonb)->>$1)::int8 > $2 where.append("((").append(at).append("::jsonb)") - .append("->>").append(placeholderForArg(op.key)).append(")::").append(pgType) + .append("->>").append(placeholderForArg(op.key)).append("::").append(pgType).append(")") .append(">").append(placeholderForArg(value, pgType)) } is TagGte -> { @@ -206,7 +216,7 @@ internal class PgQueryWhereBuilder(private val request: ReadFeatures, private va if (negate) where.append("NOT ") // [NOT ]((foo::jsonb)->>$1)::int8 >= $2 where.append("((").append(at).append("::jsonb)") - .append("->>").append(placeholderForArg(op.key)).append(")::").append(pgType) + .append("->>").append(placeholderForArg(op.key)).append("::").append(pgType).append(")") .append(">=").append(placeholderForArg(value, pgType)) } is TagLt -> { @@ -215,7 +225,7 @@ internal class PgQueryWhereBuilder(private val request: ReadFeatures, private va if (negate) where.append("NOT ") // [NOT ]((foo::jsonb)->>$1)::int8 < $2 where.append("((").append(at).append("::jsonb)") - .append("->>").append(placeholderForArg(op.key)).append(")::").append(pgType) + .append("->>").append(placeholderForArg(op.key)).append("::").append(pgType).append(")") .append("<").append(placeholderForArg(value, pgType)) } is TagLte -> { @@ -224,15 +234,17 @@ internal class PgQueryWhereBuilder(private val request: ReadFeatures, private va if (negate) where.append("NOT ") // [NOT ]((foo::jsonb)->>$1)::int8 <= $2 where.append("((").append(at).append("::jsonb)") - .append("->>").append(placeholderForArg(op.key)).append(")::").append(pgType) + .append("->>").append(placeholderForArg(op.key)).append("::").append(pgType).append(")") .append("<=").append(placeholderForArg(value, pgType)) } is TagStartsWith -> { + val pgType = PgType.ofValue(op.value) ?: throw illegalArg("The given value is no valid argument for ${op.op}}: ${op.value}") + val value = pgType.convertValue(op.value) // [NOT ]starts_with(((foo::jsonb)->>$1), $2) if (negate) where.append("NOT ") where.append("starts_with(((").append(at).append("::jsonb)") - .append("->>").append(placeholderForArg(op.key)).append(")::").append(PgType.STRING) - .append(", ").append(placeholderForArg(op.value)).append(") ") + .append("->>").append(placeholderForArg(op.key)).append("::").append(pgType).append(")") + .append(", ").append(placeholderForArg(value, pgType)).append(") ") } is TagListContains -> { // A tag list is stored as text[]; single-element membership: = ANY(tags) does not use GIN; tags @> ARRAY[] does use GIN @@ -370,7 +382,7 @@ internal class PgQueryWhereBuilder(private val request: ReadFeatures, private va } } - private fun whereFeatureId() { + private fun whereFeatureId() { // Partition into numeric IDs (fn >= 0, id stored as NULL in DB) and named IDs (fn < 0, id NOT NULL). val reqIds: StringList = request.featureIds val featureNumbers: MutableList = mutableListOf() diff --git a/here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/InsertFeatureTest.kt b/here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/InsertFeatureTest.kt index 98bec494c..6a3841ddb 100644 --- a/here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/InsertFeatureTest.kt +++ b/here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/InsertFeatureTest.kt @@ -13,6 +13,11 @@ import naksha.psql.assertions.NakshaFeatureFluidAssertions.Companion.assertThatF import naksha.model.RandomFeatures.RandomFeatures_C.randomFeature import naksha.model.RandomFeatures.RandomFeatures_C.randomFeatures import naksha.model.objects.NakshaFeature +import naksha.model.objects.StandardMembers +import naksha.model.objects.StandardMembers.StandardMembers_C.Tn +import naksha.model.objects.XyzMembers.XyzMembers_C.XyzId +import naksha.model.objects.XyzMembers.XyzMembers_C.XyzTn +import naksha.model.request.ops.Equals import kotlin.test.* class InsertFeatureTest : PgTestBase() { @@ -136,6 +141,18 @@ class InsertFeatureTest : PgTestBase() { } .hasTags(TagList("wicked")) } + + executeRead(ReadFeatures().apply { + catalogId = collection.catalogId + collectionId = collection.id + queryMembers = Equals(XyzId, "$featureNumber") + }).apply { + assertEquals(1, features.size) + val f = assertNotNull(features[0]) + assertEquals("$featureNumber", f.id) + val tn = assertNotNull( XyzTn.readTupleNumber(f) ) + assertEquals(featureNumber, tn.featureNumber.toLong()) + } } @Test From 10db243c8d32740159d1f53d5525b1290b9c8e98 Mon Sep 17 00:00:00 2001 From: Alexander Lowey-Weber Date: Thu, 27 Aug 2026 17:01:01 +0200 Subject: [PATCH 02/41] Add some helper methods to convert AnyList into typed arrays. Signed-off-by: Alexander Lowey-Weber --- .../commonMain/kotlin/naksha/base/AnyList.kt | 227 ++++++++++++++++++ 1 file changed, 227 insertions(+) diff --git a/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/AnyList.kt b/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/AnyList.kt index 571886e38..010b1a741 100644 --- a/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/AnyList.kt +++ b/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/AnyList.kt @@ -2,6 +2,7 @@ package naksha.base +import naksha.base.Platform.PlatformCompanion.toJSON import kotlin.js.JsExport /** @@ -23,4 +24,230 @@ open class AnyList : ListProxy(Any::class) { return this } + /** + * Convert this list into an integer-array. + * @param convertNonBoolean if _true_ all elements not being [Boolean] are converted into boolean; otherwise an exception is thrown. + * @return this list as [BooleanArray]. + * @throws NakshaException with error [ILLEGAL_STATE][NakshaError.ILLEGAL_STATE] if `convertNonBoolean` is _false_ and an element is no boolean. + * @since 3.0 + */ + fun toBooleanArray(convertNonBoolean: Boolean): BooleanArray { + val array = BooleanArray(size) + var end = 0 + for (i in 0 until size) { + val item = get(i) + if (item is Boolean) { + array[end++] = item + } else if (convertNonBoolean) { + array[end++] = when (item) { + is String -> "true".equals(item, ignoreCase = true) + is Float -> item != 0.0f + is Double -> item != 0.0 + is Number -> item.toLong() != 0L + else -> false + } + } else throw illegalState("The element at index $i is no boolean") + } + return if (end == array.size) array else array.copyOf(end) + } + + /** + * Convert this list into an short-array. + * @param ignoreIllegalValues if _true_ invalid elements, `null` elements, or elements not being in the valid short range are ignored; otherwise an exception is thrown. + * @return this list as [ShortArray]. + * @throws NakshaException with error [ILLEGAL_STATE][NakshaError.ILLEGAL_STATE] if `ignoreIllegalValues` is _false_ and an element is no 16-bit integer, this includes integers being out of the valid 16-bit range _(so being too small or large)_. + * @since 3.0 + */ + fun toShortArray(ignoreIllegalValues: Boolean): ShortArray { + val array = ShortArray(size) + var end = 0 + for (i in 0 until size) { + val item = get(i) + if (item is Number) { + val value = item.toLong() + if (value in Short.MIN_VALUE.toLong() .. Short.MAX_VALUE.toLong()) { + array[end++] = value.toShort() + continue + } + } + if (!ignoreIllegalValues) { + throw illegalState("The element at index $i is no valid short") + } + } + return if (end == array.size) array else array.copyOf(end) + } + + /** + * Convert this list into an integer-array. + * @param ignoreIllegalValues if _true_ invalid elements, `null` elements, or elements not being in the valid integer range are ignored; otherwise an exception is thrown. + * @return this list as [IntArray]. + * @throws NakshaException with error [ILLEGAL_STATE][NakshaError.ILLEGAL_STATE] if `ignoreIllegalValues` is _false_ and an element is no 32-bit integer, this includes integers being out of the valid 32-bit range _(so being too small or large)_. + * @since 3.0 + */ + fun toIntArray(ignoreIllegalValues: Boolean): IntArray { + val array = IntArray(size) + var end = 0 + for (i in 0 until size) { + val item = get(i) + if (item is Number) { + val value = item.toLong() + if (value in Int.MIN_VALUE.toLong() .. Int.MAX_VALUE.toLong()) { + array[end++] = value.toInt() + continue + } + } + if (!ignoreIllegalValues) { + throw illegalState("The element at index $i is no valid integer") + } + } + return if (end == array.size) array else array.copyOf(end) + } + + /** + * Convert this list into an integer-array. + * @param ignoreIllegalValues if _true_ invalid elements, `null` elements, or elements not being in the valid integer range are ignored; otherwise an exception is thrown. + * @return this list as [LongArray]. + * @throws NakshaException with error [ILLEGAL_STATE][NakshaError.ILLEGAL_STATE] if `ignoreIllegalValues` is _false_ and an elements is no 64-bit integer. + * @since 3.0 + */ + fun toLongArray(ignoreIllegalValues: Boolean): LongArray { + val array = LongArray(size) + var end = 0 + for (i in 0 until size) { + val item = get(i) + if (item is Number) { + array[end++] = item.toLong() + continue + } + if (!ignoreIllegalValues) { + throw illegalState("The element at index $i is no valid long") + } + } + return if (end == array.size) array else array.copyOf(end) + } + + /** + * Convert this list into a float-array. + * @param ignoreIllegalValues if _true_ invalid elements, `null` elements are ignored; otherwise an exception is thrown. + * @return this list as [DoubleArray]. + * @throws NakshaException with error [ILLEGAL_STATE][NakshaError.ILLEGAL_STATE] if `ignoreIllegalValues` is _false_ and an elements is no number. + * @since 3.0 + */ + fun toFloatArray(ignoreIllegalValues: Boolean): FloatArray { + val array = FloatArray(size) + var end = 0 + for (i in 0 until size) { + val item = get(i) + if (item is Number) { + array[end++] = item.toFloat() + continue + } + if (!ignoreIllegalValues) { + throw illegalState("The element at index $i is no valid number") + } + } + return if (end == array.size) array else array.copyOf(end) + } + + /** + * Convert this list into a double-array. + * @param ignoreIllegalValues if _true_ invalid elements, `null` elements are ignored; otherwise an exception is thrown. + * @return this list as [DoubleArray]. + * @throws NakshaException with error [ILLEGAL_STATE][NakshaError.ILLEGAL_STATE] if `ignoreIllegalValues` is _false_ and an elements is no number. + * @since 3.0 + */ + fun toDoubleArray(ignoreIllegalValues: Boolean): DoubleArray { + val array = DoubleArray(size) + var end = 0 + for (i in 0 until size) { + val item = get(i) + if (item is Number) { + array[end++] = item.toDouble() + continue + } + if (!ignoreIllegalValues) { + throw illegalState("The element at index $i is no valid number") + } + } + return if (end == array.size) array else array.copyOf(end) + } + + /** + * Convert this list into an array of [ByteArray]. + * @param ignoreIllegalValues if _true_ elements not being a [ByteArray] are ignored; otherwise an exception is thrown. + * @return this list as array of strings. + * @throws NakshaException with error [ILLEGAL_STATE][NakshaError.ILLEGAL_STATE] if `ignoreIllegalValues` is _false_ and an element is no [ByteArray]. + * @since 3.0 + */ + fun toByteArrayArray(ignoreIllegalValues: Boolean): Array { + val array = arrayOfNulls(size) + var end = 0 + for (i in 0 until size) { + val item = get(i) + if (item is ByteArray) { + array[end++] = item + continue + } + if (!ignoreIllegalValues) { + throw illegalState("The element at index $i is no valid string") + } + } + @Suppress("UNCHECKED_CAST") + return (if (end == array.size) array else array.copyOf(end)) as Array + } + + /** + * Convert this list into a string-array. + * @param ignoreIllegalValues if _true_ elements not being string are ignored; otherwise an exception is thrown. + * @return this list as array of strings. + * @throws NakshaException with error [ILLEGAL_STATE][NakshaError.ILLEGAL_STATE] if `ignoreIllegalValues` is _false_ and an element is no string. + * @since 3.0 + */ + fun toStringArray(ignoreIllegalValues: Boolean): Array { + val array = arrayOfNulls(size) + var end = 0 + for (i in 0 until size) { + val item = get(i) + if (item is String) { + array[end++] = item + continue + } + if (!ignoreIllegalValues) { + throw illegalState("The element at index $i is no valid string") + } + } + @Suppress("UNCHECKED_CAST") + return (if (end == array.size) array else array.copyOf(end)) as Array + } + + /** + * Convert this list into a string-array. + * @param invalidToNull if _true_ invalid elements are turned into `null` values. + * @param ignoreIllegalValues if `invalidToNull` is _false_ and this argument is _true_, invalid elements are ignored _(be removed from the returned list)_; otherwise an exception is thrown for invalid elements. + * @return this list as array of strings, may contain `null` values. + * @throws NakshaException with error [ILLEGAL_STATE][NakshaError.ILLEGAL_STATE] if `ignoreIllegalValues` is _false_ and an element is neither `null` nor a string. + * @since 3.0 + */ + fun toStringNullableArray(invalidToNull: Boolean, ignoreIllegalValues: Boolean): Array { + val array = arrayOfNulls(size) + var end = 0 + for (i in 0 until size) { + var item = get(i) + if (item != null && item !is String) { + if (invalidToNull) item = null + else if (ignoreIllegalValues) continue + else throw illegalState("The element at index $i is no valid string") + } + array[end++] = item + } + return if (end == array.size) array else array.copyOf(end) + } + + /** + * Convert this list into a string-array that contains all elements `JSON` serialized. + * @return this list as a string-array of `JSON` serialized elements. + * @since 3.0 + */ + fun toJsonArray(): Array = Array(size) { toJSON(it) } + } From 92e9ce91218dcf66b6ba2567f4351b9b6079efce Mon Sep 17 00:00:00 2001 From: Alexander Lowey-Weber Date: Thu, 27 Aug 2026 17:01:37 +0200 Subject: [PATCH 03/41] Add helper to try to proxy any type. Signed-off-by: Alexander Lowey-Weber --- .../src/commonMain/kotlin/naksha/base/LibBase.kt | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/LibBase.kt b/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/LibBase.kt index ddd051284..f1380154a 100644 --- a/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/LibBase.kt +++ b/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/LibBase.kt @@ -6,6 +6,7 @@ package naksha.base import kotlin.reflect.KClass +import kotlin.reflect.cast inline fun Int64(value: Long) = Platform.longToInt64(value) inline fun Int64(value: Int) = Platform.toInt64(value) @@ -73,6 +74,20 @@ inline fun AtomicRef(referee: T?): AtomicRef = Platform.newAtomicRe inline fun AtomicNonNullRef(referee: T): AtomicNonNullRef = Platform.newAtomicNonNullRef(referee) inline fun WeakRef(referee: T): WeakRef = Platform.newWeakRef(referee) +/** + * Cast this, if possible, into the given proxy. + * @param klass the proxy class to return. + * @return this as the requested proxy or `null`. + * @since 3.0 + */ +inline fun Any?.proxy(klass: KClass): T? { + if (this == null) return null + if (klass.isInstance(this)) return klass.cast(this) + if (this is PlatformMap) return this.proxy(klass) + if (this is Proxy) return this.proxy(klass) + return null +} + /** * Create a proxy or return the existing proxy. * @param klass the proxy class. From b52532a66e4356ee6de99d4f48ad332c6319e64a Mon Sep 17 00:00:00 2001 From: Alexander Lowey-Weber Date: Thu, 27 Aug 2026 17:02:30 +0200 Subject: [PATCH 04/41] Split featureNumber function for performance improvement at other places. Signed-off-by: Alexander Lowey-Weber --- .../commonMain/kotlin/naksha/model/Naksha.kt | 51 +++++++++++++------ 1 file changed, 35 insertions(+), 16 deletions(-) diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/Naksha.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/Naksha.kt index 7448cc162..c1990be9c 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/Naksha.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/Naksha.kt @@ -11,7 +11,6 @@ import naksha.geo.GeoUtil.GeoUtil_C.toTWKB import naksha.geo.SpGeometry import naksha.base.NakshaError.NakshaErrorCompanion.ILLEGAL_ARGUMENT import naksha.base.NakshaError.NakshaErrorCompanion.STORAGE_NOT_FOUND -import naksha.base.Version.VersionCompanion.virtualVersion import naksha.model.NakshaVersion.Companion.CURRENT import naksha.model.objects.NakshaStorage import kotlin.js.JsExport @@ -179,22 +178,16 @@ class Naksha private constructor() { /** * A method to calculate a valid database-number from the database-id. * + * The method simply invokes [featureNumber]. + * * @param id the id, from which to extract the database-number. * @return the database-number. * @since 3.0 - * @see [hashId] + * @see [featureNumber] */ @JsStatic @JvmStatic - fun databaseNumber(id: String): Int64 { - if (id == "0" || is63BitUnsigned.matches(id)) { - try { - return id.toLong(10).toInt64() - } catch (_: Exception) {} - } - val md5 = hashId(id) - return md5.getInt64(8) or INT64_SIGN_BIT - } + fun databaseNumber(id: String): Int64 = featureNumber(id) /** * A method to calculate a valid catalog-number from the catalog-id. @@ -242,7 +235,9 @@ class Naksha private constructor() { /** * A method to calculate the feature-number (`fn`) from the feature-id. * - * Actually, this method will try to detect if the feature-id is a 63-bit unsigned integer, if that is the case, it will convert this string into the corresponding positive 64-bit integer, and return it. + * Actually, this method will try to detect if the feature-id is a 63-bit unsigned integer using [featureNumberAsLong], if that is the case, it will convert this string into the corresponding positive 64-bit integer, and return it. If [featureNumberAsLong] returns `-1`, so the `id` is no valid positive numeric identifier, it will invoke [featureNumberAsHash] to convert the `id` into a 64-bit hash identifier, which is guaranteed to be a negative number. + * + * Applications may have performance advantages when they process identifiers in a loop to apply this logic themself to avoid unnecessary hashing or duplicate number parsing/detection. * * Otherwise, it uses the [MD5](https://en.wikipedia.org/wiki/MD5) hash above the feature-id and return the lower 64-bit as feature-number, with the highest bit (sign-bit) always being cleared, which reserves all positive numbers for manually managed feature-numbers, which is compatible to what `Map-Hub` originally did. Considering the [birthday paradox](https://betterexplained.com/articles/understanding-the-birthday-paradox/), we can assume that for the maximum of 2^40 features in a collection, there will be around 65,000 collisions, when using 2^32 features _(4 billion)_ we only get 2 collisions, while for less than 1 billion features we will not encounter any collision _(or, it is unlikely)_. * @@ -259,19 +254,43 @@ class Naksha private constructor() { * * @param id the feature-id, from which to extract the feature-number. * @return the feature-number. - * @see [hashId] - * @see [alternativeInt64] + * @see [featureNumberAsLong] + * @see [featureNumberAsHash] */ @JsStatic @JvmStatic fun featureNumber(id: String): Int64 { + val numericId = featureNumberAsLong(id) + return if (numericId >= 0L) numericId.toInt64() else featureNumberAsHash(id) + } + + /** + * Converts the given feature `id` into a 64-bit positive feature-number if the given `id` is a valid positive integer in the supported range. + * + * This method is faster than [featureNumber] if the feature-number is only needed, when it is positive. Internally used when detecting numeric identifies in query building. This method does not apply an [MD5](https://en.wikipedia.org/wiki/MD5) hash. + * @param id the feature-id as string. + * @return the feature-id as positive number, when being a positive number; `-1` otherwise. + * @since 3.0 + */ + @JsStatic + @JvmStatic + fun featureNumberAsLong(id: String): Long { val internalNumber = internalIdToNumber[id] - if (internalNumber != null) return internalNumber.toInt64() + if (internalNumber != null) return internalNumber.toLong() if (id == "0" || is63BitUnsigned.matches(id)) { try { - return id.toLong(10).toInt64() + return id.toLong(10) } catch (_: Exception) {} } + return -1L + } + + /** + * + */ + @JsStatic + @JvmStatic + fun featureNumberAsHash(id: String): Int64 { val md5 = hashId(id) return md5.getInt64(8) or INT64_SIGN_BIT } From accc50fdb2450f0aed58fc67370614396c8ea1b1 Mon Sep 17 00:00:00 2001 From: Alexander Lowey-Weber Date: Thu, 27 Aug 2026 17:02:54 +0200 Subject: [PATCH 05/41] Fix that isInstance of members accept normal lists for TAG_MAP_FROM_ARRAY Signed-off-by: Alexander Lowey-Weber --- .../commonMain/kotlin/naksha/model/objects/MemberType.kt | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/MemberType.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/MemberType.kt index 1221e689f..64fed33e3 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/MemberType.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/MemberType.kt @@ -198,8 +198,7 @@ class MemberType : JsEnum() { * @return `true` if the value is of this type; false otherwise. */ fun isInstance(value: Any?): Boolean { - if (value == null) return false - return when (this) { + return value != null && when (this) { BOOLEAN -> value is Boolean INT8 -> value is Byte INT16 -> value is Byte || value is Short @@ -211,8 +210,8 @@ class MemberType : JsEnum() { BYTE_ARRAY -> value is ByteArray TUPLE_NUMBER -> value is TupleNumber SPATIAL -> value is SpGeometry - TAG_MAP, TAG_MAP_FROM_ARRAY -> value is TagMap - TAG_LIST -> value is List<*> + TAG_MAP -> value is TagMap + TAG_MAP_FROM_ARRAY, TAG_LIST -> value is List<*> else -> false } } From 48e95f66f2147d130140ca57a597001b582697e9 Mon Sep 17 00:00:00 2001 From: Alexander Lowey-Weber Date: Thu, 27 Aug 2026 17:03:49 +0200 Subject: [PATCH 06/41] Add missing TAGLIST_CONTAINS, fix any type can be provided to detect op type, optimized casts Signed-off-by: Alexander Lowey-Weber --- .../kotlin/naksha/model/request/ops/Op.kt | 82 +++++++++++-------- 1 file changed, 48 insertions(+), 34 deletions(-) diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/ops/Op.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/ops/Op.kt index a4e0e1967..632c8a0f8 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/ops/Op.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/ops/Op.kt @@ -6,6 +6,10 @@ import naksha.base.AnyObject import naksha.base.MapProxy import naksha.base.NotNullProperty import naksha.base.NullableProperty +import naksha.base.Platform +import naksha.base.Platform.PlatformCompanion.toJSON +import naksha.base.illegalArg +import naksha.base.proxy import kotlin.js.ExperimentalJsExport import kotlin.js.ExperimentalJsStatic import kotlin.js.JsExport @@ -45,7 +49,9 @@ import kotlin.jvm.JvmStatic @JsExport open class Op : AnyObject() { companion object MemberOp_C { - private val STRING = NotNullProperty(String::class) + private val OP_STRING = NotNullProperty(String::class) { self, name -> + throw illegalArg("Missing '$name' property or no valid string: ${toJSON(self)}") + } private val STRING_OR_NULL = NullableProperty(String::class) const val AND = "and" @@ -82,50 +88,58 @@ open class Op : AnyObject() { /** * Auto-detect the concrete type of member operation and return the cast real type. - * @param op the member-operation to detect the real type. - * @return the real [Op] instance or just `null`, if no real type is known. + * @param op the object to detect the real operation from. + * @return the real [Op] instance _(for example [Equals], [Gt], ...)_. + * @since 3.0 + * @throws naksha.base.NakshaException with [ILLEGAL_ARGUMENT][naksha.base.NakshaError.ILLEGAL_ARGUMENT] error, when the given operation, or it's name (`op` property) is invalid/unknown. */ @JvmStatic @JsStatic - fun detect(op: MapProxy<*,*>): Op? { - if (op is Op && op::class != Op::class) return op - return when(op.getRaw("op") as String?) { - AND -> op.proxy(And::class) - OR -> op.proxy(Or::class) - NOT -> op.proxy(Not::class) - IS_NULL -> op.proxy(IsNull::class) - IS_TRUE -> op.proxy(IsTrue::class) - IS_FALSE -> op.proxy(IsFalse::class) - EQ -> op.proxy(Equals::class) - GT -> op.proxy(Gt::class) - GTE -> op.proxy(Gte::class) - LT -> op.proxy(Lt::class) - LTE -> op.proxy(Lte::class) - STARTS_WITH -> op.proxy(StartsWith::class) - IS_ANY_OF -> op.proxy(IsAnyOf::class) - INTERSECTS -> op.proxy(Intersects::class) - TAGMAP_HAS_KEY -> op.proxy(TagMapHasKey::class) - TAGMAP_HAS_ANY_OF -> op.proxy(TagMapHasAnyOf::class) - TAGMAP_HAS_ALL_OF -> op.proxy(TagMapHasAllOf::class) - TAG_IS_NULL -> op.proxy(TagIsNull::class) - TAG_EQ -> op.proxy(TagEquals::class) - TAG_STARTS_WITH -> op.proxy(TagStartsWith::class) - TAG_MATCHES -> op.proxy(TagMatches::class) - TAG_GT -> op.proxy(TagGt::class) - TAG_GTE -> op.proxy(TagGte::class) - TAG_LT -> op.proxy(TagLt::class) - TAG_LTE -> op.proxy(TagLte::class) - TAGLIST_CONTAINS_ANY_OF -> op.proxy(TagListContainsAnyOf::class) - TAGLIST_CONTAINS_ALL_OF -> op.proxy(TagListContainsAllOf::class) + fun detect(op: Any?): Op { + val realOp = op as? Op? ?: op.proxy(Op::class) + ?: throw illegalArg("The given operation is not detectable: ${toJSON(op)}") + val opName = realOp.op + val opProxy = when(opName) { + AND -> op as? And ?: op.proxy(And::class) + OR -> op as? Or ?: op.proxy(Or::class) + NOT -> op as? Not ?: op.proxy(Not::class) + IS_NULL -> op as? IsNull ?: op.proxy(IsNull::class) + IS_TRUE -> op as? IsTrue ?: op.proxy(IsTrue::class) + IS_FALSE -> op as? IsFalse ?: op.proxy(IsFalse::class) + EQ -> op as? Equals ?: op.proxy(Equals::class) + GT -> op as? Gt ?: op.proxy(Gt::class) + GTE -> op as? Gte ?: op.proxy(Gte::class) + LT -> op as? Lt ?: op.proxy(Lt::class) + LTE -> op as? Lte ?: op.proxy(Lte::class) + STARTS_WITH -> op as? StartsWith ?: op.proxy(StartsWith::class) + IS_ANY_OF -> op as? IsAnyOf ?: op.proxy(IsAnyOf::class) + INTERSECTS -> op as? Intersects ?: op.proxy(Intersects::class) + TAGMAP_HAS_KEY -> op as? TagMapHasKey ?: op.proxy(TagMapHasKey::class) + TAGMAP_HAS_ANY_OF -> op as? TagMapHasAnyOf ?: op.proxy(TagMapHasAnyOf::class) + TAGMAP_HAS_ALL_OF -> op as? TagMapHasAllOf ?: op.proxy(TagMapHasAllOf::class) + TAG_IS_NULL -> op as? TagIsNull ?: op.proxy(TagIsNull::class) + TAG_EQ -> op as? TagEquals ?: op.proxy(TagEquals::class) + TAG_STARTS_WITH -> op as? TagStartsWith ?: op.proxy(TagStartsWith::class) + TAG_MATCHES -> op as? TagMatches ?: op.proxy(TagMatches::class) + TAG_GT -> op as? TagGt ?: op.proxy(TagGt::class) + TAG_GTE -> op as? TagGte ?: op.proxy(TagGte::class) + TAG_LT -> op as? TagLt ?: op.proxy(TagLt::class) + TAG_LTE -> op as? TagLte ?: op.proxy(TagLte::class) + TAGLIST_CONTAINS -> op as? TagListContains ?: op.proxy(TagListContains::class) + TAGLIST_CONTAINS_ANY_OF -> op as? TagListContainsAnyOf ?: op.proxy(TagListContainsAnyOf::class) + TAGLIST_CONTAINS_ALL_OF -> op as? TagListContainsAllOf ?: op.proxy(TagListContainsAllOf::class) else -> null } + return opProxy ?: throw illegalArg("Unknown operation: $opName") } } /** * The operation identifier. + * + * Throws [NakshaException][naksha.base.NakshaException] with error [ILLEGAL_ARGUMENT][naksha.base.NakshaError.ILLEGAL_ARGUMENT] if the `op` property is no valid string. Does not verify if the name is a valid and supported one, only ensures that the `op` property is a string. */ - var op: String by STRING + var op: String by OP_STRING /** * The name of the member to query; if any _(some operations do not work upon members)_. From 20c82ad363599c2fd050f8d969d2b07ddb604584 Mon Sep 17 00:00:00 2001 From: Alexander Lowey-Weber Date: Thu, 27 Aug 2026 17:04:21 +0200 Subject: [PATCH 07/41] Improve documentation of Tag queries, clarify that they operate on value, not key. Signed-off-by: Alexander Lowey-Weber --- .../src/commonMain/kotlin/naksha/model/request/ops/TagEquals.kt | 2 +- .../src/commonMain/kotlin/naksha/model/request/ops/TagGt.kt | 2 +- .../src/commonMain/kotlin/naksha/model/request/ops/TagGte.kt | 2 +- .../src/commonMain/kotlin/naksha/model/request/ops/TagIsNull.kt | 2 +- .../src/commonMain/kotlin/naksha/model/request/ops/TagLt.kt | 2 +- .../src/commonMain/kotlin/naksha/model/request/ops/TagLte.kt | 2 +- .../commonMain/kotlin/naksha/model/request/ops/TagStartsWith.kt | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/ops/TagEquals.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/ops/TagEquals.kt index 46134e0db..ebf9f2306 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/ops/TagEquals.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/ops/TagEquals.kt @@ -9,7 +9,7 @@ import kotlin.js.JsExport import kotlin.js.JsName /** - * Tests if the tag [key] on the member at [at] equals the given [value]. + * Tests if the value of the tag [key] on the member [at] equals the given [value]. The value may be `null`, in that case this is the same as [TagIsNull]. * @since 3.0 */ @JsExport diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/ops/TagGt.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/ops/TagGt.kt index d16f232ce..ed56a8912 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/ops/TagGt.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/ops/TagGt.kt @@ -9,7 +9,7 @@ import kotlin.js.JsExport import kotlin.js.JsName /** - * Tests if the tag [key] on the member at [at] is greater than the given [value]. + * Tests if the value of the tag [key] on the member [at] is greater than the given [value]. * @since 3.0 */ @JsExport diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/ops/TagGte.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/ops/TagGte.kt index d65c9fb74..4ec75c061 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/ops/TagGte.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/ops/TagGte.kt @@ -9,7 +9,7 @@ import kotlin.js.JsExport import kotlin.js.JsName /** - * Tests if the tag [key] on the member at [at] is greater than or equal to the given [value]. + * Tests if the value of the tag [key] on the member [at] is greater than or equal to the given [value]. * @since 3.0 */ @JsExport diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/ops/TagIsNull.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/ops/TagIsNull.kt index f25b660c7..fdbcc5249 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/ops/TagIsNull.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/ops/TagIsNull.kt @@ -8,7 +8,7 @@ import kotlin.js.JsExport import kotlin.js.JsName /** - * Tests if the tag [key] on the member at [at] is null. + * Tests if the value of the tag [key] on the member [at] is `null`. * @since 3.0 */ @JsExport diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/ops/TagLt.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/ops/TagLt.kt index 890772433..251ac89fe 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/ops/TagLt.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/ops/TagLt.kt @@ -9,7 +9,7 @@ import kotlin.js.JsExport import kotlin.js.JsName /** - * Tests if the tag [key] on the member at [at] is less than the given [value]. + * Tests if the value of the tag [key] on the member [at] is less than the given [value]. * @since 3.0 */ @JsExport diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/ops/TagLte.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/ops/TagLte.kt index ad4ece3e8..3a3317c96 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/ops/TagLte.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/ops/TagLte.kt @@ -9,7 +9,7 @@ import kotlin.js.JsExport import kotlin.js.JsName /** - * Tests if the tag [key] on the member at [at] is less than or equal to the given [value]. + * Tests if the value of the tag [key] on the member [at] is less than or equal to the given [value]. * @since 3.0 */ @JsExport diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/ops/TagStartsWith.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/ops/TagStartsWith.kt index 8a61471fb..efad30580 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/ops/TagStartsWith.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/ops/TagStartsWith.kt @@ -8,7 +8,7 @@ import kotlin.js.JsExport import kotlin.js.JsName /** - * Tests if the tag [key] on the member at [at] starts with the given [value]. + * Tests if the value of the tag [key] on the member [at] is a string and starts with the given [value]. * @since 3.0 */ @JsExport From 730ad7ad0daee21493e64cc4d00e515219b1e4e8 Mon Sep 17 00:00:00 2001 From: Alexander Lowey-Weber Date: Thu, 27 Aug 2026 17:05:01 +0200 Subject: [PATCH 08/41] Remove catching of exceptions, leaving this to the caller, needed for debugging and stack-tracing. Signed-off-by: Alexander Lowey-Weber --- .../commonMain/kotlin/naksha/psql/PgReader.kt | 63 +++++++++---------- 1 file changed, 29 insertions(+), 34 deletions(-) diff --git a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgReader.kt b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgReader.kt index 49e87b0a0..28fc3a54d 100644 --- a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgReader.kt +++ b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgReader.kt @@ -35,43 +35,38 @@ class PgReader( get() = session.useTransaction().version fun execute(): Response { - try { - val session = this.session - val query = PgQueryBuilder(session, request).build() - val conn = session.useConnection() - session.storage.adminCatalog.setSearchPath(conn) - if (PlatformUtil.ENABLE_INFO) { - if (session.logQueries) { - session.logAtInfo(query.sql) - } - if (session.logExplain) { - val explain = session.explain(conn, false, query.sql, query.argTypes, query.argValues) - session.logAtInfo(explain) - } + val session = this.session + val query = PgQueryBuilder(session, request).build() + val conn = session.useConnection() + session.storage.adminCatalog.setSearchPath(conn) + if (PlatformUtil.ENABLE_INFO) { + if (session.logQueries) { + session.logAtInfo(query.sql) } - conn.prepare(query.sql, query.argTypes).use { plan -> - // Start allocating around 8 KiB - val featureTuples = FeatureTupleList() - featureTuples.setCapacity(1024) - // Note: We know that each result is only 12 or 20 byte - plan.setFetchSize(1_000_000) // Set very high to encourage parallelism on server side - // https://www.cybertec-postgresql.com/en/parallel-query-postgresql-problems-jdbc-dbeaver/ - plan.execute(query.argValues).use { cursor -> - val storageNumber = query.storageNumber - val mapNumber = query.mapNumber - val collectionNumber = query.collectionNumber - while (cursor.next()) { - val col_num: Int = collectionNumber ?: cursor["col_num"] - val fn: naksha.base.Int64 = cursor["fn"] - val version: naksha.base.Int64 = cursor["version"] - featureTuples.add(FeatureTuple(TupleNumber(storageNumber, mapNumber, col_num, fn, version))) - } + if (session.logExplain) { + val explain = session.explain(conn, false, query.sql, query.argTypes, query.argValues) + session.logAtInfo(explain) + } + } + conn.prepare(query.sql, query.argTypes).use { plan -> + // Start allocating around 8 KiB + val featureTuples = FeatureTupleList() + featureTuples.setCapacity(1024) + // Note: We know that each result is only 12 or 20 byte + plan.setFetchSize(1_000_000) // Set very high to encourage parallelism on server side + // https://www.cybertec-postgresql.com/en/parallel-query-postgresql-problems-jdbc-dbeaver/ + plan.execute(query.argValues).use { cursor -> + val storageNumber = query.storageNumber + val mapNumber = query.mapNumber + val collectionNumber = query.collectionNumber + while (cursor.next()) { + val col_num: Int = collectionNumber ?: cursor["col_num"] + val fn: naksha.base.Int64 = cursor["fn"] + val version: naksha.base.Int64 = cursor["version"] + featureTuples.add(FeatureTuple(TupleNumber(storageNumber, mapNumber, col_num, fn, version))) } - return SuccessResponse().withFeatureTupleList(featureTuples) } - } catch (e: Exception) { - val nakshaException = PgExceptionMapper.map(e) - return ErrorResponse(nakshaException) + return SuccessResponse().withFeatureTupleList(featureTuples) } } } From 1ac0ea419f8e08f41a3be9acd9dd60ae756dcd93 Mon Sep 17 00:00:00 2001 From: Alexander Lowey-Weber Date: Thu, 27 Aug 2026 17:05:58 +0200 Subject: [PATCH 09/41] Fix convertValue to work with all values, rename childType to componentType, add kotlin klass of types. Signed-off-by: Alexander Lowey-Weber --- .../commonMain/kotlin/naksha/psql/PgType.kt | 168 ++++++++++++++---- 1 file changed, 134 insertions(+), 34 deletions(-) diff --git a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgType.kt b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgType.kt index ca4d972b5..482779634 100644 --- a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgType.kt +++ b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgType.kt @@ -2,8 +2,14 @@ package naksha.psql +import naksha.base.AnyList +import naksha.base.Int64 import naksha.base.JsEnum import naksha.base.ListProxy +import naksha.base.Platform.PlatformCompanion.toJSON +import naksha.base.illegalArg +import naksha.base.internalError +import naksha.base.proxy import naksha.model.objects.Member import naksha.model.objects.MemberType import kotlin.js.JsExport @@ -20,110 +26,157 @@ import kotlin.reflect.KClass class PgType : JsEnum() { companion object { // https://www.postgresql.org/docs/current/datatype.html + + /** + * The PostgresSQ data type for `null`, being `null`. + * @since 3.0 + */ @JvmField @JsStatic val NULL = defIgnoreCase(PgType::class, "null") { it.byteSize = 0 } + /** + * The PostgresSQ data type for [Boolean], being `boolean`. + * @since 3.0 + */ @JvmField @JsStatic val BOOLEAN = defIgnoreCase(PgType::class, "boolean") { it.byteSize = 1 + it.klass = Boolean::class }.alias("bool") @JvmField @JsStatic val BOOLEAN_ARRAY = defIgnoreCase(PgType::class, "boolean[]") { - it.isArray = true - it.childType = BOOLEAN + it.componentType = BOOLEAN + it.klass = BooleanArray::class }.alias("bool[]") + /** + * The PostgresSQ data type for [Short], being `int2`. + * @since 3.0 + */ @JvmField @JsStatic val SHORT = defIgnoreCase(PgType::class, "int2") { it.byteSize = 2 + it.klass = Short::class }.alias("smallint") @JvmField @JsStatic val SHORT_ARRAY = defIgnoreCase(PgType::class, "int2[]") { - it.isArray = true - it.childType = SHORT + it.componentType = SHORT + it.klass = ShortArray::class }.alias("smallint[]") + /** + * The PostgresSQ data type for [Int], being `int4`. + * @since 3.0 + */ @JvmField @JsStatic val INT = defIgnoreCase(PgType::class, "int4") { it.byteSize = 4 + it.klass = Int::class }.alias("int").alias("integer") @JvmField @JsStatic val INT_ARRAY = defIgnoreCase(PgType::class, "int4[]") { - it.isArray = true - it.childType = INT + it.componentType = INT + it.klass = IntArray::class }.alias("int[]").alias("integer[]") + /** + * The PostgresSQ data type for [Long], being `int8`. + * @since 3.0 + */ @JvmField @JsStatic val INT64 = defIgnoreCase(PgType::class, "int8") { it.byteSize = 8 + it.klass = Long::class }.alias("bigint") @JvmField @JsStatic val INT64_ARRAY = defIgnoreCase(PgType::class, "int8[]") { - it.isArray = true - it.childType = INT64 + it.componentType = INT64 + it.klass = LongArray::class }.alias("bigint[]") + /** + * The PostgresSQ data type for [Float], being `float4`. + * @since 3.0 + */ @JvmField @JsStatic val FLOAT = defIgnoreCase(PgType::class, "float4") { it.byteSize = 4 + it.klass = Float::class }.alias("real") @JvmField @JsStatic val FLOAT_ARRAY = defIgnoreCase(PgType::class, "float4[]") { - it.isArray = true - it.childType = FLOAT + it.componentType = FLOAT + it.klass = FloatArray::class }.alias("real[]") + /** + * The PostgresSQ data type for [Double], being `float8`. + * @since 3.0 + */ @JvmField @JsStatic val DOUBLE = defIgnoreCase(PgType::class, "float8") { it.byteSize = 8 + it.klass = Double::class }.alias("double precision") @JvmField @JsStatic val DOUBLE_ARRAY = defIgnoreCase(PgType::class, "float8[]") { - it.isArray = true - it.childType = DOUBLE + it.componentType = DOUBLE + it.klass = DoubleArray::class }.alias("double precision[]") + /** + * The PostgresSQ data type for [String], being `text`. + * @since 3.0 + */ @JvmField @JsStatic - val STRING = defIgnoreCase(PgType::class, "text") + val STRING = defIgnoreCase(PgType::class, "text") { + it.klass = String::class + } @JvmField @JsStatic val STRING_ARRAY = defIgnoreCase(PgType::class, "text[]") { - it.isArray = true - it.childType = STRING + it.componentType = STRING + it.klass = Array::class } + /** + * The PostgresSQ data type for [ByteArray], being `bytea`. + * @since 3.0 + */ @JvmField @JsStatic - val BYTE_ARRAY = defIgnoreCase(PgType::class, "bytea") + val BYTE_ARRAY = defIgnoreCase(PgType::class, "bytea") { + it.klass = ByteArray::class + } @JvmField @JsStatic val BYTE_ARRAY_ARRAY = defIgnoreCase(PgType::class, "bytea[]") { - it.isArray = true - it.childType = BYTE_ARRAY + it.componentType = BYTE_ARRAY + it.klass = Array::class } /** @@ -134,7 +187,9 @@ class PgType : JsEnum() { */ @JvmField @JsStatic - val JSONB = defIgnoreCase(PgType::class, "jsonb") + val JSONB = defIgnoreCase(PgType::class, "jsonb") { + it.klass = String::class + } /** * `jsonb[]` array type. Element values are JSON text strings (the on-wire form Postgres accepts for `jsonb`). @@ -144,8 +199,8 @@ class PgType : JsEnum() { @JvmField @JsStatic val JSONB_ARRAY = defIgnoreCase(PgType::class, "jsonb[]") { - it.isArray = true - it.childType = JSONB + it.componentType = JSONB + it.klass = Array::class } /** @@ -159,13 +214,19 @@ class PgType : JsEnum() { /** * Detects the [PgType] of the given value, if it has any. + * + * If the given `value` is `null`, then [NULL] is returned, the value `null` means that the detection failed. + * + * ### WARNING + * This method is unable to detect [JSONB] type! * @param value the value for which to detect the [PgType] - * @return the matching [PgType] or `null`, if none matches. + * @return the matching [PgType] or `null` if none matches. */ @JsStatic @JvmStatic fun ofValue(value: Any?): PgType? { when (value) { + null -> return NULL is Boolean -> return BOOLEAN is Byte -> return SHORT is Short -> return SHORT @@ -175,7 +236,8 @@ class PgType : JsEnum() { is Double -> return DOUBLE is String -> return STRING is ByteArray -> return BYTE_ARRAY - is List<*>, is ListProxy<*> -> { + is List<*>, + is ListProxy<*> -> { val elementType = value.firstOrNull()?.let { ofValue(it) } ?: return null return when (elementType) { BOOLEAN -> BOOLEAN_ARRAY @@ -235,27 +297,36 @@ class PgType : JsEnum() { override fun initClass() {} + /** + * The [KClass] of the type. + * + * ### Warning + * Kotlin sadly does not support real typed arrays, so for example for `Array` is not supported, you will get `Array::class`! + * @since 3.0 + */ + var klass: KClass<*>? = null + private set + /** * The size of the type, when being stored and not _null_, or `-1`, if the type has a dynamic * @since 3.0 */ var byteSize: Int = -1 - get() = if (field == null) -1 else field + get() = if (field == null) -1 else field // Note: JavaScript hack! private set /** * If this type is an array. * @since 3.0 */ - var isArray: Boolean = false - get() = if (field == null) false else field - private set + val isArray: Boolean + get() = componentType != null /** - * If this is an array, the child type. + * If this is an array, the type of the elements _(aka component type)_. * @since 3.0 */ - var childType: PgType? = null + var componentType: PgType? = null private set /** @@ -264,13 +335,42 @@ class PgType : JsEnum() { * For example, converts a `List` into a `String[]`. * @param value the value to convert into this type. * @return the value so that it can be used with JDBC. + * @throws naksha.base.NakshaException if the value can't be converted. */ fun convertValue(value: Any?): Any? { - // TODO: We need to convert certain values to postgres valid ones - // For lists, we need to convert them into typed arrays. - return when (value) { - is ListProxy<*>, is List<*> -> value.toTypedArray() - else -> value + return when (this) { + NULL -> null + BOOLEAN -> value as? Boolean? + ?: throw illegalArg("The given value is not a boolean: $value") + SHORT, INT -> (value as? Number?)?.toInt() + ?: throw illegalArg("The given value is no number: $value") + INT64 -> if (value is Number) value.toLong() else if (value is Int64) value.toLong() + else throw illegalArg("The given value is no number: $value") + FLOAT -> (value as? Number?)?.toFloat() + ?: throw illegalArg("The given value is no number: $value") + DOUBLE -> (value as? Number?)?.toDouble() + ?: throw illegalArg("The given value is no number: $value") + STRING -> value as? String? + ?: throw illegalArg("The given value is not a string: $value") + BYTE_ARRAY -> value as? ByteArray? + ?: throw illegalArg("The given value is not a string: $value") + JSONB -> toJSON(value) + + BOOLEAN_ARRAY -> value as? BooleanArray ?: (value.proxy(AnyList::class)?.toBooleanArray(true) + ?: throw illegalArg("The given value is not an list: $value")) + SHORT_ARRAY -> value as? ShortArray ?: value.proxy(AnyList::class)?.toShortArray(true) + ?: throw illegalArg("The given value is not an list: $value") + INT_ARRAY -> value as? IntArray ?: value.proxy(AnyList::class)?.toIntArray(true) + ?: throw illegalArg("The given value is not an list: $value") + INT64_ARRAY -> value as? LongArray ?: value.proxy(AnyList::class)?.toLongArray(true) + ?: throw illegalArg("The given value is not an list: $value") + // We do not support Array, it's hard to detect cross-platform! + BYTE_ARRAY_ARRAY -> value.proxy(AnyList::class)?.toByteArrayArray(true) + ?: throw illegalArg("The given value is not an list: $value") + // We do not support Array, it's hard to detect cross-platform! + JSONB_ARRAY -> value.proxy(AnyList::class)?.toJsonArray() + ?: throw illegalArg("The given value is not an list: $value") + else -> throw internalError("Missing when-case for this Postgres Type: $this") } } } \ No newline at end of file From 9d75b32fadc6c1bebeef0d6626c90c2ace9c63ee Mon Sep 17 00:00:00 2001 From: Alexander Lowey-Weber Date: Thu, 27 Aug 2026 17:07:17 +0200 Subject: [PATCH 10/41] Log all errors with stack-trace for better debugging, the error response does not contain stack trace! Signed-off-by: Alexander Lowey-Weber --- .../src/commonMain/kotlin/naksha/psql/PgSession.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgSession.kt b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgSession.kt index 6397a16e5..5612e7b83 100644 --- a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgSession.kt +++ b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgSession.kt @@ -282,8 +282,8 @@ open class PgSession( } return response } catch (t: Throwable) { + logger.info("PgSession: execute failed", t) val nakshaException = PgExceptionMapper.map(t) - nakshaException.error.print() return ErrorResponse(nakshaException.error) } } From a0e1a3056a7ce9d2b08394314b6a7d15deee5e0f Mon Sep 17 00:00:00 2001 From: Alexander Lowey-Weber Date: Thu, 27 Aug 2026 17:08:06 +0200 Subject: [PATCH 11/41] Use json_array_elements_text and add explicit cast, jsonb is slower here, because this is a one-time call. Signed-off-by: Alexander Lowey-Weber --- .../src/commonMain/kotlin/naksha/psql/PgRows.kt | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgRows.kt b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgRows.kt index d45b8cff4..3e01fe50c 100644 --- a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgRows.kt +++ b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgRows.kt @@ -535,8 +535,9 @@ internal class PgRows { fun newRowProjection(): String = columns.joinToString(", ") { val ident = PgUtil.quoteIdent(it.alias) if (it.pgColumn.memberType == MemberType.TAG_LIST) - "CASE WHEN $ident IS NULL THEN NULL ELSE ARRAY(SELECT jsonb_array_elements_text($ident)) END AS $ident" - else ident + "CASE WHEN $ident IS NULL THEN NULL ELSE ARRAY(SELECT json_array_elements_text($ident::json)) END AS $ident" + else + ident } /** From 51e5bc903c45bbcc05a5086a33593edbbc19b898 Mon Sep 17 00:00:00 2001 From: Alexander Lowey-Weber Date: Thu, 27 Aug 2026 17:08:53 +0200 Subject: [PATCH 12/41] Improve array handling, whenever possible use native array without converting, improve type detection. Signed-off-by: Alexander Lowey-Weber --- .../jvmMain/kotlin/naksha/psql/PsqlQuery.kt | 232 +++++++++++------- 1 file changed, 140 insertions(+), 92 deletions(-) diff --git a/here-naksha-lib-psql/src/jvmMain/kotlin/naksha/psql/PsqlQuery.kt b/here-naksha-lib-psql/src/jvmMain/kotlin/naksha/psql/PsqlQuery.kt index ea3a267b5..f24e60a6e 100644 --- a/here-naksha-lib-psql/src/jvmMain/kotlin/naksha/psql/PsqlQuery.kt +++ b/here-naksha-lib-psql/src/jvmMain/kotlin/naksha/psql/PsqlQuery.kt @@ -1,31 +1,15 @@ package naksha.psql import naksha.base.Int64 +import naksha.base.JvmInt64 import naksha.base.ListProxy import naksha.base.MapProxy import naksha.base.Platform import naksha.base.illegalArg -import naksha.psql.PgType.Companion.BOOLEAN -import naksha.psql.PgType.Companion.BOOLEAN_ARRAY -import naksha.psql.PgType.Companion.BYTE_ARRAY -import naksha.psql.PgType.Companion.BYTE_ARRAY_ARRAY -import naksha.psql.PgType.Companion.DOUBLE -import naksha.psql.PgType.Companion.DOUBLE_ARRAY -import naksha.psql.PgType.Companion.FLOAT -import naksha.psql.PgType.Companion.FLOAT_ARRAY -import naksha.psql.PgType.Companion.INT -import naksha.psql.PgType.Companion.INT64 -import naksha.psql.PgType.Companion.INT64_ARRAY -import naksha.psql.PgType.Companion.INT_ARRAY -import naksha.psql.PgType.Companion.JSONB -import naksha.psql.PgType.Companion.JSONB_ARRAY -import naksha.psql.PgType.Companion.SHORT -import naksha.psql.PgType.Companion.SHORT_ARRAY -import naksha.psql.PgType.Companion.STRING -import naksha.psql.PgType.Companion.STRING_ARRAY import java.sql.Connection import java.sql.PreparedStatement import java.sql.ResultSet.* +import kotlin.reflect.KClass /** * A helper to parse SQL queries and find the dollar-placeholders, replacing them with `?`, escape question-marks, and finally provide a @@ -34,10 +18,17 @@ import java.sql.ResultSet.* class PsqlQuery(query: String, private val typeNames: Array?) { /** - * We map "$1" to a list of positions (`1..n`) in the prepared statement. For example - * `SELECT * FROM table WHERE a = $1 OR b = $1`. In that case, we replace it with - * `SELECT * FROM table WHERE a = ? OR b = ?` and the map holds one entry 1 and a - * list of two elements 1 and 2. + * A map of placeholder positions (`1..n`) in the prepared statement. + * + * For example + * ```sql + * SELECT * FROM table WHERE a=$1 OR b=$1 + * ``` + * In that case JDBC requires: + * ```sql + * SELECT * FROM table WHERE a=? OR b=? + * ``` + * This map will then contain a key `1` _(which is the dollar-index)_, assigned to an array with the JDBC indices to bind. In this case `1` and `2`. When binding the arguments the code needs to bind it to all indices. Beware that JDBC positions start at index `1` not `0` and the index array contains already the correct JDBC values, so all values will be between `1` and `n` _(inclusive)_! */ val dollarToIndices: HashMap> = HashMap() val sql: String @@ -87,83 +78,129 @@ class PsqlQuery(query: String, private val typeNames: Array?) { } } - private fun setArgument(stmt: PreparedStatement, arg: Any?, indices: ArrayList) { - var i = 0 - while (i < indices.size) { - // Note: `index` starts with 1, NOT 0 !!! - val index = indices[i++] - when (arg) { - null -> stmt.setNull(index, 0) - is Boolean -> stmt.setBoolean(index, arg) - is Short -> stmt.setShort(index, arg) - is Int -> stmt.setInt(index, arg) - is Long -> stmt.setLong(index, arg) - is Int64 -> stmt.setLong(index, arg.toLong()) - is Float -> stmt.setFloat(index, arg) - is Double -> stmt.setDouble(index, arg) - is String -> stmt.setString(index, arg) - is ByteArray -> stmt.setBytes(index, arg) - is Array<*> -> { - // Note: Java array indices start at 0, NOT 1 !!! - val typeNameIndex = index - 1 - val typeName = if (typeNames != null && typeNameIndex < typeNames.size) typeNames[typeNameIndex] else null - var type = PgType.of(typeName) - if (type == null) { - if (arg.size == 0) throw illegalArg("Can't detect type of empty array, declared type: $typeName") - var j = 0 - while (type == null && j < arg.size) { - val testValue = arg[j++] - type = when (testValue) { - null -> null - is Boolean -> BOOLEAN_ARRAY - is Short -> SHORT_ARRAY - is Int -> INT_ARRAY - is Int64, is Long -> INT64_ARRAY - is Float -> FLOAT_ARRAY - is Double -> DOUBLE_ARRAY - is String -> STRING_ARRAY - is ByteArray -> BYTE_ARRAY_ARRAY - else -> throw illegalArg("Auto detection of array-type failed due to unknown value for \$$index, declared type: $typeName, found type: ${testValue::class.simpleName}") + /** + * Binds the given argument in the given prepared statement. + * + * Beware that we support the natural PostgresQL syntax, which allows to refer the same value multiple times, so for example `WHERE a = $1 OR b = $1` is allowed, however, in JDBC we have to translate this into `WHERE a = ? OR b = ?` and we now need to bind both placeholders to the same value. Therefore, the argument `indices` provides the zero-based indices in the query where the corresponding question mark is located. This means, we may need to bind the same argument multiple times. + * @param stmt the statement. + * @param arg the value to bind. + * @param typeName the type name as specified in the prepared statement; if any is available. + * @param indices a list of indices to bind the argument to. + */ + private fun setArgument(stmt: PreparedStatement, arg: Any?, typeName: String?, indices: ArrayList) { + val conn = stmt.connection + when (arg) { + // Note: `index` in JDBC starts with 1, NOT 0! + null -> for (index in indices) stmt.setNull(index, 0) + // Recursive call, simply convert the list into an array, then it's handled below. + is ListProxy<*> -> setArgument(stmt, arg.toArray(), typeName, indices) + // Wrapped primitives. + is Boolean -> for (index in indices) stmt.setBoolean(index, arg) + is Byte -> for (index in indices) stmt.setShort(index, arg.toShort()) + is Short -> for (index in indices) stmt.setShort(index, arg) + is Int -> for (index in indices) stmt.setInt(index, arg) + is Long -> for (index in indices) stmt.setLong(index, arg) + is Int64 -> for (index in indices) stmt.setLong(index, arg.toLong()) + is Float -> for (index in indices) stmt.setFloat(index, arg) + is Double -> for (index in indices) stmt.setDouble(index, arg) + is String -> for (index in indices) stmt.setString(index, arg) + is CharSequence -> for (index in indices) stmt.setString(index, arg.toString()) + // Handle Primitive Arrays. + // https://jdbc.postgresql.org/documentation/server-prepare/#arrays + is ByteArray -> for (index in indices) stmt.setBytes(index, arg) + is BooleanArray -> for (index in indices) stmt.setObject(index, arg) + is ShortArray -> for (index in indices) stmt.setObject(index, arg) + is IntArray -> for (index in indices) stmt.setObject(index, arg) + is LongArray -> for (index in indices) stmt.setObject(index, arg) + is FloatArray -> for (index in indices) stmt.setObject(index, arg) + is DoubleArray -> for (index in indices) stmt.setObject(index, arg) + // Handle Array<*>. + is Array<*> -> { + // https://jdbc.postgresql.org/documentation/server-prepare/#arrays + var componentType = arg.javaClass.componentType!! + var array: Array<*> = arg + if (componentType == Any::class.java || componentType == Int64::class.java || componentType == JvmInt64::class.java) { + // Special handling for `Array`: + // Array of objects need to be turned either into a `java.sql.Array` or converted into a `Array`. + // The reason is that the driver only accepts arrays with same content, and if the content is null, + // it still needs to know the type. + // We treat Int64 as Long until we switched finally! + if (componentType == Int64::class.java || componentType == JvmInt64::class.java) { + componentType = Long::class.javaObjectType + } else for (value in arg) { + if (value == null) continue + componentType = value.javaClass + if (componentType == Int64::class.java || componentType == JvmInt64::class.java) { + componentType = Long::class.javaObjectType + } + break + } + if (componentType == Any::class.java) { + // Try to detect the component type from what the client provided in the prepared statement. + if (typeName != null) { + val pgType = PgType.of(typeName) + if (pgType != null) { + val klass: KClass<*>? = if (pgType.isArray) pgType.componentType?.klass else pgType.klass + if (klass != null) componentType = klass.javaObjectType } } } - when (type) { - BOOLEAN_ARRAY, - SHORT_ARRAY, - INT_ARRAY, - INT64_ARRAY, - FLOAT_ARRAY, - DOUBLE_ARRAY, - STRING_ARRAY, - JSONB_ARRAY -> { - stmt.setArray(index, stmt.connection.createArrayOf(type.childType!!.text, arg)) + // Convert into component array. + array = when (componentType) { + Boolean::class.javaObjectType -> Array(array.size) { + val v = arg[it] + if (v != null && v !is Boolean) throw illegalArg("Illegal value in Boolean array at $it: '$v'") + v + } + Short::class.javaObjectType -> Array(array.size) { + val v = arg[it] + if (v != null && v !is Short) throw illegalArg("Illegal value in Short array at $it: '$v'") + v + } + Int::class.javaObjectType -> Array(array.size) { + val v = arg[it] + if (v != null && v !is Int) throw illegalArg("Illegal value in Int array at $it: '$v'") + v } - BYTE_ARRAY_ARRAY -> { - // This is a hack, because we need a `Byte[][]`, JDBC does not support an `Object[][]`, - // even while the content may be the same, and it knows the type, still - // Note: I guess the driver supports Object[][] for other types, because it can invoke - // helpers like `toString`, `toInt`, `toLong`, ... on them, but there is no such thing - // for byte-arrays (byte[]), and instead of writing an own toByteArray, they fail! - val arr = Array(arg.size) { arg[it] as ByteArray? } - stmt.setArray(index, stmt.connection.createArrayOf(type.childType!!.text, arr)) + Long::class.javaObjectType -> Array(array.size) { + var v = arg[it] + if (v is Int64) v = v.toLong() + if (v != null && v !is Long) throw illegalArg("Illegal value in Long array at $it: '$v'") + v } - BOOLEAN, - SHORT, - INT, - INT64, - FLOAT, - DOUBLE, - STRING, - BYTE_ARRAY, - JSONB -> throw illegalArg("The argument is $type, but an array was provided as value") - null -> throw illegalArg("Failed to detect array type, no type-name was provided (null)") - else -> throw illegalArg("Failed to detect array type, and invalid type-name was provided: $typeName") + Float::class.javaObjectType -> Array(array.size) { + val v = arg[it] + if (v != null && v !is Float) throw illegalArg("Illegal value in Float array at $it: '$v'") + v + } + Double::class.javaObjectType -> Array(array.size) { + val v = arg[it] + if (v != null && v !is Double) throw illegalArg("Illegal value in Double array at $it: '$v'") + v + } + String::class.java -> Array(array.size) { + val v = arg[it] + if (v != null && v !is String) throw illegalArg("Illegal value in String array at $it: '$v'") + v + } + ByteArray::class.java -> Array(array.size) { + val v = arg[it] + if (v != null && v !is ByteArray) throw illegalArg("Illegal value in ByteArray array at $it: '$v'") + v + } + else -> throw illegalArg("Can't detect correct component type of empty arrays or arrays with only null values") } } - is ListProxy<*> -> setArgument(stmt, arg.toArray(), indices) - is MapProxy<*, *> -> stmt.setString(index, Platform.toJSON(arg)) - else -> throw illegalArg("Unable to set argument: args[${index - 1}], unknown type: ${arg.javaClass.name}") + if (!validComponentJavaTypes.contains(componentType)) { + throw illegalArg("Unsupported array type: ${componentType.name}") + } + for (index in indices) stmt.setObject(index, array) + } + is MapProxy<*, *> -> { + val json = Platform.toJSON(arg) + for (index in indices) stmt.setString(index, json) } + else -> throw illegalArg("Failed to bind argument to query, unsupported type: ${arg::class.qualifiedName}") } } @@ -171,9 +208,10 @@ class PsqlQuery(query: String, private val typeNames: Array?) { var i = 0 while (i < args.size) { val arg = args[i] + val typeName = typeNames?.get(i) val indices = dollarToIndices[i + 1] check(indices != null) { "Indices must not be null - could not resolve index for \$${i + 1}" } - setArgument(stmt, arg, indices) + setArgument(stmt, arg, typeName, indices) i++ } } @@ -186,5 +224,15 @@ class PsqlQuery(query: String, private val typeNames: Array?) { private const val SUSPICIOUSLY_MANY_ARGS = 1_000 private val positiveNums = '1'..'9' private val nums = '0'..'9' + private val validComponentJavaTypes = setOf>( + Short::class.javaObjectType, Short::class.javaPrimitiveType!!, + Int::class.javaObjectType, Int::class.javaPrimitiveType!!, + Long::class.javaObjectType, Long::class.javaPrimitiveType!!, + Float::class.javaObjectType, Float::class.javaPrimitiveType!!, + Double::class.javaObjectType, Double::class.javaPrimitiveType!!, + Boolean::class.javaObjectType, Boolean::class.javaPrimitiveType!!, + String::class.java, + ByteArray::class.java + ) } } From fa02d8feeee904bbfd6d57b6a66339523e143d9b Mon Sep 17 00:00:00 2001 From: Alexander Lowey-Weber Date: Thu, 27 Aug 2026 17:09:22 +0200 Subject: [PATCH 13/41] Fix tag-map queries to use index and fix that queries on `id` work for numeric identifiers. Signed-off-by: Alexander Lowey-Weber --- .../kotlin/naksha/psql/PgQueryWhereBuilder.kt | 675 +++++++++++++----- 1 file changed, 477 insertions(+), 198 deletions(-) diff --git a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgQueryWhereBuilder.kt b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgQueryWhereBuilder.kt index 31524a084..f5ec62d68 100644 --- a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgQueryWhereBuilder.kt +++ b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgQueryWhereBuilder.kt @@ -1,17 +1,30 @@ package naksha.psql +import naksha.base.AnyList import naksha.base.Int64 import naksha.base.StringList import naksha.model.Naksha import naksha.base.NakshaError import naksha.base.NakshaException import naksha.base.illegalArg +import naksha.base.unsupportedOp +import naksha.geo.SpGeometry +import naksha.model.Naksha.NakshaCompanion.featureNumberAsLong +import naksha.model.objects.MemberType import naksha.model.objects.StandardMembers -import naksha.model.objects.XyzMembers +import naksha.model.objects.StandardMembers.StandardMembers_C.Action +import naksha.model.objects.StandardMembers.StandardMembers_C.FeatureNumber +import naksha.model.objects.StandardMembers.StandardMembers_C.FeatureVersion +import naksha.model.objects.StandardMembers.StandardMembers_C.Id +import naksha.model.objects.StandardMembers.StandardMembers_C.Tn +import naksha.model.objects.XyzMembers.XyzMembers_C.XyzAuthorTimestamp +import naksha.model.objects.XyzMembers.XyzMembers_C.XyzCreatedAt +import naksha.model.objects.XyzMembers.XyzMembers_C.XyzUpdatedAt import naksha.model.request.ReadFeatures import naksha.model.request.ops.* import naksha.psql.PgColumn.PgColumn_C.FnColumn import naksha.psql.PgColumn.PgColumn_C.VersionColumn +import naksha.psql.PgType.Companion.NULL /** * Helper to convert a [ReadFeatures] request into a sql `WHERE` query. @@ -23,9 +36,22 @@ import naksha.psql.PgColumn.PgColumn_C.VersionColumn * @see [build] */ internal class PgQueryWhereBuilder(private val request: ReadFeatures, private val collection: PgCollection) { - + /** + * The WHERE clause. + * @since 3.0 + */ val where = StringBuilder() + + /** + * The values of the arguments in order, the entry at index `0` matches the argument `$1`. + * @since 3.0 + */ val argValues: MutableList = mutableListOf() + + /** + * The PostgresQL data types of the arguments in order, the entry at index `0` matches the argument `$1`. + * @since 3.0 + */ val argTypes: MutableList = mutableListOf() /** @@ -36,17 +62,15 @@ internal class PgQueryWhereBuilder(private val request: ReadFeatures, private va fun build(): PgQueryWhereClause? { var op: Op? = request.queryMembers if (op == null) { - // Note: ReadFeatures clearly states, that `queryMembers` always wins, so we only recognize if op is null! + // When no `queryMembers` is given, we apply backward compatibility. op = QueryConverter.convert(request.query) - // Only read everything when there is no filter at all — featureIds/guids apply even when op is null. if (op == null && request.featureIds.isEmpty() && request.guids.isEmpty()) return null - if (request.featureIds.isNotEmpty()) { // TODO backward compatibility for feature IDs read requests, to be removed - whereFeatureId() - } - if (request.guids.isNotEmpty()) { // TODO backward compatibility for GUIDs read requests, remove if nowhere else is using it - whereGuids() - } + if (request.featureIds.isNotEmpty()) whereFeatureId() + if (request.guids.isNotEmpty()) whereGuids() + if (op != null) applyOp(op) } else { + // ReadFeatures clearly states that you have to use either the new syntax or the old, not mix them! + // Note: We want to get people to switch to new syntax, not start improving old queries with new features! if (request.query.isNotEmpty()) throw illegalArg("Old 'query' option must not be combined with new 'queryMember'") if (request.featureIds.isNotEmpty()) @@ -55,12 +79,52 @@ internal class PgQueryWhereBuilder(private val request: ReadFeatures, private va throw illegalArg("Old 'guids' option must not be combined with new 'queryMember'") applyOp(op) } + if (where.isEmpty()) return null return PgQueryWhereClause(collection, where.toString(), argValues, argTypes) } + /** + * Returns the column name of the given member or the extracted value for virtual members. + * + * **Does not work for `id`, because the value is needed special hack is needed!** + **/ + private fun memberColumn(memberName: String): String = when (memberName) { + Tn.name -> throw illegalArg("Query at tuple-number (Tn) member is not supported by lib-psql") + Action.name -> "((${VersionColumn.name} & 3)::int4)" + XyzCreatedAt.name, XyzAuthorTimestamp.name -> "COALESCE($memberName, ${XyzUpdatedAt.name})" + else -> memberName + } + + /** + * Returns the given value, if it is a valid value matching the type of the member. + * + * The method treats a `null` value as always valid, it is up to the caller to decide if `null` is acceptable in the concrete situation. + * @param memberName the name of the member. + * @param opName the name of the operation to perform. + * @param value the value to test. + * @param memberType the data-type of the member, which much match that of the given value. + * @return the real column name to query and the real valid value to query against. + * @throws NakshaException if the given value is not of the desired member-type. + */ + private fun columnAndValue(memberName: String, opName: String, value: Any?, memberType: MemberType): Pair { + if (value != null && !memberType.isInstance(value)) { + throw illegalArg("The value for '$memberName' $opName '$value' is not the correct type, excepted: $memberType") + } + return if (memberName == Id.name) { + val numeric = featureNumberAsLong(value as String) + // If `id` is a string, but a positive integer, the `id` column will be NULL. + // Therefore, in that case we need to search for the intger in the feature-number (fn) column! + if (numeric >= 0) Pair(FeatureNumber.name, numeric) else Pair(Id.name, value) + } else Pair(memberColumn(memberName), value) + } + + /** + * Update [where], [argValues] and [argTypes] from the given operation(s). + * @since 3.0 + */ private fun applyOp(rawOp: Op, negate: Boolean = false) { - val opName = rawOp.op - val op = Op.detect(rawOp) ?: throw illegalArg("Unknown operation: '$opName'") + val opName = rawOp.getRaw("op") as? String? ?: throw illegalArg("Unknown operation, 'op' property is no string") + val op = Op.detect(rawOp) when (op) { is And -> { if (negate) where.append(" NOT ") @@ -93,202 +157,420 @@ internal class PgQueryWhereBuilder(private val request: ReadFeatures, private va return } } - val rawAt: String = op.at ?: throw illegalArg("Missing member name for operation $opName") - // The action is virtual: resolve it to the version bit-mask instead of a physical column. - val isAction = rawAt == StandardMembers.Action.name - val at: String = when { - isAction -> "(${VersionColumn.name} & 3)::int4" - rawAt == XyzMembers.XyzCreatedAt.name || rawAt == XyzMembers.XyzAuthorTimestamp.name -> - "COALESCE($rawAt, ${XyzMembers.XyzUpdatedAt.name})" - else -> rawAt + val memberName: String = op.at ?: throw illegalArg("Missing 'at' (member name) for operation '$opName'") + val memberType = collection.column(memberName)?.memberType ?: when (memberName) { + Action.name -> MemberType.INT32 + FeatureVersion.name -> MemberType.INT64 + FeatureNumber.name -> MemberType.INT64 + Tn.name -> throw illegalArg("PgQueryWhereBuilder: The tuple-number can't be queried in lib-psql") + else -> throw illegalArg("PgQueryWhereBuilder: Unknown member '$memberName' in collection '${collection.id}'") } when (op) { - is IsNull -> { - if (negate) - where.append(at).append(" IS NOT NULL").append(' ') - else - where.append(at).append(" IS NULL").append(' ') - } - is IsTrue -> { - if (negate) - where.append(at).append('=').append(placeholderForArg(false, PgType.BOOLEAN)).append(' ') - else - where.append(at).append('=').append(placeholderForArg(true, PgType.BOOLEAN)).append(' ') - } - is IsFalse -> { - if (negate) - where.append(at).append('=').append(placeholderForArg(true, PgType.BOOLEAN)).append(' ') - else - where.append(at).append('=').append(placeholderForArg(false, PgType.BOOLEAN)).append(' ') - } - is Equals -> { - val value: Any? = op.value - if (value == null) { - if (negate) where.append(at).append(" IS NOT NULL ") else where.append(at).append(" IS NULL ") + is IsNull -> _IsNull(negate, memberName, opName, memberType) + is IsTrue -> _IsTrue(negate, memberName, opName, memberType) + is IsFalse -> _IsFalse(negate, memberName, opName, memberType) + is Equals -> _Equals(negate, memberName, opName, op.value, memberType) + is Gt -> _Gt(negate, memberName, opName, op.value, memberType) + is Gte -> _Gte(negate, memberName, opName, op.value, memberType) + is Lt -> _Lt(negate, memberName, opName, op.value, memberType) + is Lte -> _Lte(negate, memberName, opName, op.value, memberType) + is StartsWith -> _StartsWith(negate, memberName, opName, op.value, memberType) + is IsAnyOf -> _IsAnyOf(negate, memberName, opName, op.items, memberType) + is TagMapHasKey -> _TagMapHasKey(negate, memberName, op.key) + is TagMapHasAnyOf -> _TagMapHasAnyOf(negate, memberName, op.tagKeys) + is TagMapHasAllOf -> _TagMapHasAllOf(negate, memberName, op.tagKeys) + is TagIsNull -> _TagIsNull(negate, memberName, op.key) + is TagEquals -> _TagEquals(negate, memberName, op.key, op.value) + is TagGt -> _TagGt(negate, memberName, op.key, op.value) + is TagGte -> _TagGte(negate, memberName, op.key, op.value) + is TagLt -> _TagLt(negate, memberName, op.key, op.value) + is TagLte -> _TagLte(negate, memberName, op.key, op.value) + is TagStartsWith -> _TagStartsWith(negate, memberName, op.key, op.value) + is TagMatches -> _TagMatches(negate, memberName, op.key, op.regex) + is TagListContains -> _TagListContains(negate, memberName, op.item) + is TagListContainsAllOf -> _TagListContainsAllOf(negate, memberName, op.items) + is TagListContainsAnyOf -> _TagListContainsAnyOf(negate, memberName, op.items) + is Intersects -> _Intersects(negate, memberName, op.value, op.transformers) + else -> throw illegalArg("PgQueryWhereBuilder: Unknown operation: '$op' at '$memberName' in collection '${collection.id}'") + } + } + + private fun _IsNull(negate: Boolean, memberName: String, opName: String, memberType: MemberType) { + val (at, _) = columnAndValue(memberName, opName, null, memberType) + if (negate) + where.append(at).append(" IS NOT NULL").append(' ') + else + where.append(at).append(" IS NULL").append(' ') + } + + private fun _IsTrue(negate: Boolean, memberName: String, opName: String, memberType: MemberType) { + val (at, _) = columnAndValue(memberName, opName, null, memberType) + if (negate) + where.append(at).append('=').append(placeholderForArg(false, PgType.BOOLEAN)).append(' ') + else + where.append(at).append('=').append(placeholderForArg(true, PgType.BOOLEAN)).append(' ') + } + + private fun _IsFalse(negate: Boolean, memberName: String, opName: String, memberType: MemberType) { + val (at, _) = columnAndValue(memberName, opName, null, memberType) + if (negate) + where.append(at).append('=').append(placeholderForArg(true, PgType.BOOLEAN)).append(' ') + else + where.append(at).append('=').append(placeholderForArg(false, PgType.BOOLEAN)).append(' ') + } + + private fun _Equals(negate: Boolean, memberName: String, opName: String, opValue: Any?, memberType: MemberType) { + val (at, value) = columnAndValue(memberName, opName, opValue, memberType) + if (value == null) { + if (negate) where.append(at).append(" IS NOT NULL ") else where.append(at).append(" IS NULL ") + } else { + val placeholder = placeholderForArg(value, at) + if (negate) + where.append(at).append("!=").append(placeholder).append(' ') + else + where.append(at).append('=').append(placeholder).append(' ') + } + } + + private fun _Gt(negate: Boolean, memberName: String, opName: String, opValue: Any?, memberType: MemberType) { + val (at, value) = columnAndValue(memberName, opName, opValue, memberType) + if (negate) // NOT Greater Than + where.append(at).append("<=").append(placeholderForArg(value, at)).append(' ') + else // Greater Than + where.append(at).append(">").append(placeholderForArg(value, at)).append(' ') + } + + private fun _Gte(negate: Boolean, memberName: String, opName: String, opValue: Any?, memberType: MemberType) { + val (at, value) = columnAndValue(memberName, opName, opValue, memberType) + if (negate) // NOT Greater Than or Equal to + where.append(at).append("<").append(placeholderForArg(value, at)).append(' ') + else // Greater Than or Equal to + where.append(at).append(">=").append(placeholderForArg(value, at)).append(' ') + } + + private fun _Lt(negate: Boolean, memberName: String, opName: String, opValue: Any?, memberType: MemberType) { + val (at, value) = columnAndValue(memberName, opName, opValue, memberType) + if (negate) // NOT Less Than + where.append(at).append(">=").append(placeholderForArg(value, at)).append(' ') + else // Less Than + where.append(at).append("<").append(placeholderForArg(value, at)).append(' ') + } + + private fun _Lte(negate: Boolean, memberName: String, opName: String, opValue: Any?, memberType: MemberType) { + val (at, value) = columnAndValue(memberName, opName, opValue, memberType) + if (negate) // NOT Less Than or Equal to + where.append(at).append(">").append(placeholderForArg(value, at)).append(' ') + else // Less Than or Equal to + where.append(at).append("<=").append(placeholderForArg(value, at)).append(' ') + } + + private fun _StartsWith(negate: Boolean, memberName: String, opName: String, opValue: Any?, memberType: MemberType) { + if (memberType != MemberType.STRING) throw illegalArg("StartsWith: The operation can only target String members") + val (at, value) = columnAndValue(memberName, opName, opValue, memberType) + if (value is Number) { + // TODO: This happens for `id`. + // We store identifiers as fature-number, when they are positive numbers. + // As we in these cases have `id` being `null`, we can't really test for starts with. + // Any solution, apart from full-table-scan, is prefered! + // Solution: + // WHERE id = 123 + // OR id BETWEEN 1230 AND 1239 + // OR id BETWEEN 12300 AND 12399 + // -- continue up to bigint's 19-digit limit + throw unsupportedOp("StartsWith: The operation is currently not implemented for numeric identifiers") + } + if (negate) where.append("NOT ") + where.append("starts_with(").append(at).append(", ").append(placeholderForArg(value, at)).append(") ") + } + + private fun _IsAnyOf(negate: Boolean, memberName: String, opName: String, items: AnyList, memberType: MemberType) { + if (items.isEmpty()) return + + // For `id` we can have a mixture of strings and numbers. + // We simply ignore invalid values being in the array. + if (memberName == Id.name) { + val fn_array = LongArray(items.size) + var fn_end = 0 + val id_array = arrayOfNulls(items.size) + var id_end = 0 + for (item in items) { + if (item !is String) continue + val numeric = featureNumberAsLong(item) + if (numeric >= 0L) { + fn_array[fn_end++] = numeric } else { - val placeholder = if (isAction) placeholderForArg(value, PgType.INT) else placeholderForArg(value) - if (negate) - where.append(at).append("!=").append(placeholder).append(' ') - else - where.append(at).append('=').append(placeholder).append(' ') - } - } - is Gt -> { - if (negate) // NOT Greater Than - where.append(at).append("<=").append(placeholderForArg(op.value)).append(' ') - else // Greater Than - where.append(at).append(">").append(placeholderForArg(op.value)).append(' ') - } - is Gte -> { - if (negate) // NOT Greater Than or Equal to - where.append(at).append("<").append(placeholderForArg(op.value)).append(' ') - else // Greater Than or Equal to - where.append(at).append(">=").append(placeholderForArg(op.value)).append(' ') - } - is Lt -> { - if (negate) // NOT Less Than - where.append(at).append(">=").append(placeholderForArg(op.value)).append(' ') - else // Less Than - where.append(at).append("<").append(placeholderForArg(op.value)).append(' ') - } - is Lte -> { - if (negate) // NOT Less Than or Equal to - where.append(at).append(">").append(placeholderForArg(op.value)).append(' ') - else // Less Than or Equal to - where.append(at).append("<=").append(placeholderForArg(op.value)).append(' ') - } - is StartsWith -> { - if (negate) where.append("NOT ") - where.append("starts_with(").append(at).append(", ").append(placeholderForArg(op.value)).append(") ") - } - is IsAnyOf -> { - if (negate) where.append("NOT ") - val arrayType = when { - isAction -> PgType.INT_ARRAY - rawAt == StandardMembers.FeatureNumber.name || - rawAt == StandardMembers.NextVersion.name || - rawAt == StandardMembers.FeatureVersion.name -> PgType.INT64_ARRAY - else -> PgType.STRING_ARRAY + id_array[id_end++] = item } - val placeholder = placeholderForArg(op.items, arrayType) - where.append(at).append("= ANY(").append(placeholder).append(") ") - } - is TagMapHasKey -> { - if (negate) where.append("NOT ") - where.append(at).append("::jsonb").append(" ?? ").append(placeholderForArg(op.key)).append(" ") - } - is TagMapHasAnyOf -> { - if (negate) where.append("NOT ") - where.append(at).append("::jsonb").append(" ??| ").append(placeholderForArg(op.tagKeys)).append(" ") - } - is TagMapHasAllOf -> { - if (negate) where.append("NOT ") - where.append(at).append("::jsonb").append(" ??& ").append(placeholderForArg(op.tagKeys)).append(" ") - } - is TagIsNull -> { - // ( foo::jsonb ? $1 AND ((foo::jsonb)->>$1) IS [NOT ]NULL) - where.append("( ") - .append(at).append("::jsonb").append(" ?? ").append(placeholderForArg(op.key)).append(" AND ") - .append("((").append(at).append("::jsonb)").append("->>").append(placeholderForArg(op.key)).append(")") - if (negate) where.append("IS NOT NULL) ") else where.append("IS NULL) ") } - is TagEquals -> { - val pgType = PgType.ofValue(op.value) ?: throw illegalArg("The given value is no valid argument for ${op.op}}: ${op.value}") - val value = pgType.convertValue(op.value) - if (negate) where.append("NOT ") - // [NOT ]((foo::jsonb)->>$1)::int8 = $2 - where.append("((").append(at).append("::jsonb)") - .append("->>").append(placeholderForArg(op.key)).append("::").append(pgType).append(")") - .append("=").append(placeholderForArg(value, pgType)) + if (negate) where.append("NOT ") + where.append('(') + if (fn_end > 0) { + val placeholder = if (fn_array.size == fn_end) placeholderForArg(fn_array, PgType.INT64_ARRAY) + else placeholderForArg(fn_array.copyOf(fn_end), PgType.INT64_ARRAY) + where.append(FeatureNumber.name).append("= ANY(").append(placeholder).append(")") } - is TagGt -> { - val pgType = PgType.ofValue(op.value) ?: throw illegalArg("The given value is no valid argument for ${op.op}}: ${op.value}") - val value = pgType.convertValue(op.value) - if (negate) where.append("NOT ") - // [NOT ]((foo::jsonb)->>$1)::int8 > $2 - where.append("((").append(at).append("::jsonb)") - .append("->>").append(placeholderForArg(op.key)).append("::").append(pgType).append(")") - .append(">").append(placeholderForArg(value, pgType)) + if (id_end > 0) { + if (fn_end > 0) where.append(" OR ") + val placeholder = if (id_array.size == id_end) placeholderForArg(id_array, PgType.STRING_ARRAY) + else placeholderForArg(id_array.copyOf(id_end), PgType.STRING_ARRAY) + where.append(Id.name).append("= ANY(").append(placeholder).append(")") } - is TagGte -> { - val pgType = PgType.ofValue(op.value) ?: throw illegalArg("The given value is no valid argument for ${op.op}}: ${op.value}") - val value = pgType.convertValue(op.value) - if (negate) where.append("NOT ") - // [NOT ]((foo::jsonb)->>$1)::int8 >= $2 - where.append("((").append(at).append("::jsonb)") - .append("->>").append(placeholderForArg(op.key)).append("::").append(pgType).append(")") - .append(">=").append(placeholderForArg(value, pgType)) - } - is TagLt -> { - val pgType = PgType.ofValue(op.value) ?: throw illegalArg("The given value is no valid argument for ${op.op}}: ${op.value}") - val value = pgType.convertValue(op.value) - if (negate) where.append("NOT ") - // [NOT ]((foo::jsonb)->>$1)::int8 < $2 - where.append("((").append(at).append("::jsonb)") - .append("->>").append(placeholderForArg(op.key)).append("::").append(pgType).append(")") - .append("<").append(placeholderForArg(value, pgType)) - } - is TagLte -> { - val pgType = PgType.ofValue(op.value) ?: throw illegalArg("The given value is no valid argument for ${op.op}}: ${op.value}") - val value = pgType.convertValue(op.value) - if (negate) where.append("NOT ") - // [NOT ]((foo::jsonb)->>$1)::int8 <= $2 - where.append("((").append(at).append("::jsonb)") - .append("->>").append(placeholderForArg(op.key)).append("::").append(pgType).append(")") - .append("<=").append(placeholderForArg(value, pgType)) - } - is TagStartsWith -> { - val pgType = PgType.ofValue(op.value) ?: throw illegalArg("The given value is no valid argument for ${op.op}}: ${op.value}") - val value = pgType.convertValue(op.value) - // [NOT ]starts_with(((foo::jsonb)->>$1), $2) - if (negate) where.append("NOT ") - where.append("starts_with(((").append(at).append("::jsonb)") - .append("->>").append(placeholderForArg(op.key)).append("::").append(pgType).append(")") - .append(", ").append(placeholderForArg(value, pgType)).append(") ") - } - is TagListContains -> { - // A tag list is stored as text[]; single-element membership: = ANY(tags) does not use GIN; tags @> ARRAY[] does use GIN - if (negate) where.append("NOT ") - where.append("(").append(at).append(" @> ").append(placeholderForArg(Array(1){op.item}, PgType.STRING_ARRAY)).append("::text[]) ") - } - is TagListContainsAllOf -> { - // tags @> $1::text[] (the list contains every requested tag) - val items = op.items.filterNotNull().toTypedArray() - if (negate) where.append("NOT ") - where.append("(").append(at).append(" @> ").append(placeholderForArg(items, PgType.STRING_ARRAY)).append("::text[]) ") - } - is TagListContainsAnyOf -> { - val items = op.items.filterNotNull().toTypedArray() - // Any-of over empty set -> false; negated -> true - if (items.isEmpty()) { - if (negate) where.append("TRUE ") else where.append("FALSE ") - return + where.append(") ") + return + } + + // For all other members the values are uniform and only one column is queried. + val at = memberColumn(memberName) + val (values, arrayType) = when(memberType) { + MemberType.INT8, + MemberType.INT16, + MemberType.INT32 -> Pair(items.toIntArray(true), PgType.INT_ARRAY) + MemberType.INT64 -> Pair(items.toLongArray(true), PgType.INT64_ARRAY) + MemberType.FLOAT32 -> Pair(items.toFloatArray(true), PgType.FLOAT_ARRAY) + MemberType.FLOAT64 -> Pair(items.toDoubleArray(true), PgType.DOUBLE_ARRAY) + MemberType.STRING -> Pair(items.toStringArray(true), PgType.STRING_ARRAY) + MemberType.BYTE_ARRAY -> Pair(items.toByteArrayArray(true), PgType.BYTE_ARRAY_ARRAY) + else -> throw illegalArg("The member '$memberName' can't be used for $opName") + } + val placeholder = placeholderForArg(values, arrayType) + if (negate) where.append("NOT ") + where.append(at).append("= ANY(").append(placeholder).append(") ") + } + + private fun _TagMapHasKey(negate: Boolean, memberName: String, key: String) { + val _key_ = placeholderForArg(key, PgType.STRING) + // jsonb ? text → boolean + // Does the text string exist as a top-level key or array element within the JSON value? + // '{"a":1, "b":2}'::jsonb ? 'b' → t + // '["a", "b", "c"]'::jsonb ? 'b' → t + if (negate) where.append("NOT ") + where.append(memberName).append(" ?? ").append(_key_).append(" ") + } + + private fun _TagMapHasAnyOf(negate: Boolean, memberName: String, keys: StringList) { + val keys_array = keys.proxy(AnyList::class).toStringArray(true) + if (keys_array.isEmpty()) return + val _keys_array_ = placeholderForArg(keys_array, PgType.STRING_ARRAY) + // jsonb ?| text[] → boolean + // Do any of the strings in the text array exist as top-level keys or array elements? + // '{"a":1, "b":2, "c":3}'::jsonb ?| array['b', 'd'] → t + if (negate) where.append("NOT ") + where.append(memberName).append(" ??| ").append(_keys_array_).append(" ") + } + + private fun _TagMapHasAllOf(negate: Boolean, memberName: String, keys: StringList) { + val keys_array = keys.proxy(AnyList::class).toStringArray(true) + if (keys_array.isEmpty()) return + val _keys_array_ = placeholderForArg(keys_array, PgType.STRING_ARRAY) + // jsonb ?& text[] → boolean + // Do all of the strings in the text array exist as top-level keys or array elements? + // '["a", "b", "c"]'::jsonb ?& array['a', 'b'] → t + if (negate) where.append("NOT ") + where.append(memberName).append(" ??& ").append(_keys_array_).append(" ") + } + + private fun _TagIsNull(negate: Boolean, memberName: String, key: String) { + val _key_ = placeholderForArg(key, PgType.STRING) + // jsonb @> jsonb → boolean + // Does the first JSON value contain the second? + // SELECT '{"a":1, "b":null}'::jsonb @> jsonb_build_object('b', null); + if (negate) where.append("NOT ") + where.append(memberName).append(" @> jsonb_build_object(").append(_key_).append(",null) ") + } + + private fun _TagEquals(negate: Boolean, memberName: String, key: String, value: Any?) { + val pg_value_type = PgType.ofValue(value) + ?: throw illegalArg("TagEquals: The given value is invalid: '$value'") + if (pg_value_type == NULL) { + _TagIsNull(negate, memberName, key) + return + } + val pg_value = pg_value_type.convertValue(value) + val _key_ = placeholderForArg(key, PgType.STRING) + val _value_ = placeholderForArg(pg_value, pg_value_type)// jsonb @> jsonb → boolean + // jsonb @> jsonb → boolean + // Does the first JSON value contain the second? + // SELECT '{"a":1, "b":null}'::jsonb @> jsonb_build_object('a', 1); + if (negate) where.append("NOT ") + where.append(memberName).append(" @> jsonb_build_object(").append(_key_).append(',').append(_value_).append(") ") + } + + private fun _TagGt(negate: Boolean, memberName: String, key: String, value: Any?) { + if (value !is Number && value !is Int64) { + throw illegalArg("TagGt: The given value is number: '$value'") + } + val expression = if (negate) "@ <= $value" else "@ > $value" + evaluateJsonPath(memberName, key, expression) + } + + private fun _TagGte(negate: Boolean, memberName: String, key: String, value: Any?) { + if (value !is Number && value !is Int64) { + throw illegalArg("TagGte: The given value is number: '$value'") + } + val expression = if (negate) "@ < $value" else "@ >= $value" + evaluateJsonPath(memberName, key, expression) + } + + private fun _TagLt(negate: Boolean, memberName: String, key: String, value: Any?) { + if (value !is Number && value !is Int64) { + throw illegalArg("TagLt: The given value is no number: '$value'") + } + val expression = if (negate) "@ >= $value" else "@ < $value" + evaluateJsonPath(memberName, key, expression) + } + + private fun _TagLte(negate: Boolean, memberName: String, key: String, value: Any?) { + if (value !is Number && value !is Int64) { + throw illegalArg("The given value is no valid tag value (number expected): $value") + } + val expression = if (negate) "@ > $value" else "@ <= $value" + evaluateJsonPath(memberName, key, expression) + } + + private fun _TagStartsWith(negate: Boolean, memberName: String, key: String, value: Any?) { + if (value !is String) { + throw illegalArg("TagStartsWith: The given value is no string: '$value'") + } + if (negate) where.append("NOT ") + val expression = "@ starts with ${quoteString(value)}" + evaluateJsonPath(memberName, key, expression) + } + + private fun _TagMatches(negate: Boolean, memberName: String, key: String, value: Any?) { + if (value !is String) { + throw illegalArg("TagMatches: The given value is no string: '$value'") + } + if (negate) where.append("NOT ") + val expression = "@ like_regex ${quoteString(value)}" + evaluateJsonPath(memberName, key, expression) + } + + private fun _TagListContains(negate: Boolean, memberName: String, item: Any?) { + val data = Array(1) { + item as? String? ?: throw illegalArg("TagListContains: The value is no string: '$item'") + } + val _value_ = placeholderForArg(data, PgType.STRING_ARRAY) + // @> —— Contains all specified elements + // When we only provide a single one, it effectively means `contains` a single one. + if (negate) where.append("NOT ") + where.append("(").append(memberName).append(" @> ").append(_value_).append("::text[]) ") + } + + private fun _TagListContainsAllOf(negate: Boolean, memberName: String, items: Any?) { + if (items !is List<*>) { + throw illegalArg("TagListContainsAllOf: The items must be a list of strings") + } + val data = Array(items.size) { + items[it] as? String? ?: throw illegalArg("TagListContainsAllOf: The item[$it] is no string") + } + val _value_ = placeholderForArg(data, PgType.STRING_ARRAY) + // @> —— Contains all specified elements + if (negate) where.append("NOT ") + where.append("(").append(memberName).append(" @> ").append(_value_).append("::text[]) ") + } + + private fun _TagListContainsAnyOf(negate: Boolean, memberName: String, items: Any?) { + if (items !is List<*>) { + throw illegalArg("TagListContainsAnyOf: The items must be a list of strings") + } + val data = Array(items.size) { + items[it] as? String? ?: throw illegalArg("TagListContainsAnyOf: The item[$it] is no string") + } + val _value_ = placeholderForArg(data, PgType.STRING_ARRAY) + // && —— Contains any specified elements + if (negate) where.append("NOT ") + where.append("(").append(memberName).append(" && ").append(_value_).append("::text[]) ") + } + + private fun _Intersects(negate: Boolean, memberName: String, geometry: SpGeometry, transformers: SpTransformationList) { + val geoBytes = Naksha.encodeGeometry(geometry) + val geoBytesPlaceholder = placeholderForArg(geoBytes, PgType.BYTE_ARRAY) + val basicGeometry = "naksha_2d($geoBytesPlaceholder)" + val geometryToCompare = if (transformers.isEmpty()) basicGeometry + else resolveTransformation(transformers, basicGeometry) + if (negate) where.append("NOT ") + where.append("ST_Intersects(naksha_2d($memberName), $geometryToCompare)") + } + + /** + * Evaluates the given `jsonpath` expression against the given key of the given `JSONB` column. + * + * A simplified general syntax for a `jsonpath` evaluations is: + * - `$.key ? (@ op value)` + * - `$` = A variable representing the JSON value being queried (the context item). + * - `.key` = Member accessor that returns an object member with the specified key. + * - `? (...)` = The expression to evaluate. + * - `@` = A variable representing the result of path evaluation in filter expressions (value of key). + * + * What need to be supplied to this method is, next to the name of the `JSONB` column, the `key` to evaluate and the expression. This is used to search in tag-map for some value. + * + * The `jsonpath` is explained in the [PostgresQL jsonpath documentation](https://www.postgresql.org/docs/18/datatype-json.html#DATATYPE-JSONPATH). The operators within a `jsonpath` expression is explained at a different part of the [PostgresQL functions-json documentation](https://www.postgresql.org/docs/18/functions-json.html#FUNCTIONS-SQLJSON-PATH-OPERATORS). + * @param memberName the name of the `JSONB` column. + * @param key the key to select and against which's value the [jsonpath operators](https://www.postgresql.org/docs/18/functions-json.html#FUNCTIONS-SQLJSON-PATH-OPERATORS) or [jsonpath filter](https://www.postgresql.org/docs/18/functions-json.html#FUNCTIONS-SQLJSON-FILTER-EX-TABLE) should be evaluated. + * @param expression the `jsonpath` expression to be evaluated, for example `@ >= 5`. + * @since 3.0 + */ + private fun evaluateJsonPath(memberName: String, key: String, expression: String) { + val _jsonpath_ = placeholderForArg( + "$.${quoteString(key)} ?? ($expression)", + PgType.STRING + ) + // jsonb @? jsonpath → boolean + // Does JSON path return any item for the specified JSON value? + // '{"a":5}'::jsonb @? '$.a ? (@ > 2)' → t + // '{"a":[1,2,3,4,5]}'::jsonb @? '$.a[*] ? (@ > 2)' → t + where.append(memberName).append(" @?? ").append(_jsonpath_) + } + + /** + * SQL-Quote the given `string`, for example: + * - `Hello "Joe" ~World` + * - Becomes: `"Hello \"Joe\" ~World"`. + * @param string the key to escape. + * @return the escaped string. + * @since 3.0 + */ + fun quoteString(string: String): String = buildString(string.length + 10) { + append('"') + for (c in string) { + when (c) { + '\\' -> append("\\\\") + '"' -> append("\\\"") + '\b' -> append("\\b") + '\u000C' -> append("\\f") + '\n' -> append("\\n") + '\r' -> append("\\r") + '\t' -> append("\\t") + in '\u0000'..'\u001F' -> { + append("\\u") + append(c.code.toString(16).padStart(4, '0')) } - // tags && $1::text[] (the list overlaps the requested tags) - if (negate) where.append("NOT ") - where.append("(").append(at).append(" && ").append(placeholderForArg(items, PgType.STRING_ARRAY)).append("::text[]) ") - } - is Intersects -> { - val geoBytes = Naksha.encodeGeometry(op.value) - val geoBytesPlaceholder = placeholderForArg(geoBytes, PgType.BYTE_ARRAY) - val queryGeometry = "naksha_2d($geoBytesPlaceholder)" - val transformation = op.transformers - val geometryToCompare = - if (transformation.isEmpty()) queryGeometry - else resolveTransformation(transformation, queryGeometry) - where.append("ST_Intersects(naksha_2d(${op.at}), $geometryToCompare)") + else -> append(c) } - else -> throw illegalArg("Unknown operation: '$op'") } + append('"') } /** * Returns a placeholder string like `$1` for the given value, and add the values and its type into the value and type arrays. + * @param value the value. + * @param at the name of the column/member for error messages. + * @throws NakshaException with error [ILLEGAL_ARGUMENT][NakshaError.ILLEGAL_ARGUMENT] if the given value is no supported valid type or `null`. + * @since 3.0 */ - private fun placeholderForArg(value: Any?): String { - // TODO: Detect the type, if not possible, throw illegalArg() - // AnyList for + ANY() - val type: PgType = PgType.STRING; + private fun placeholderForArg(value: Any?, at: String): String { + val type: PgType = when (value) { + is String -> PgType.STRING + is Boolean -> PgType.BOOLEAN + is Short -> PgType.SHORT + is Int -> PgType.INT + is Long -> PgType.INT64 + is Int64 -> PgType.INT64 + is Float -> PgType.FLOAT + is Double -> PgType.DOUBLE + is ByteArray -> PgType.BYTE_ARRAY + else -> throw illegalArg("The value for member '$at' is invalid: '$value'") + }; argValues.add(value) argTypes.add(type) return "\$${argTypes.size}" @@ -317,12 +599,9 @@ internal class PgQueryWhereBuilder(private val request: ReadFeatures, private va return "\$${argTypes.size}" } - private fun resolveTransformation( - transformationList: SpTransformationList, - basicGeometry: String - ): String { + private fun resolveTransformation(transformers: SpTransformationList, basicGeometry: String): String { var geometry = basicGeometry - for (transformation in transformationList) { + for (transformation in transformers) { geometry = when (transformation) { is SpBuffer -> resolveBuffer(transformation, geometry) else -> throw NakshaException( From cb68c9764c27101aed2c0ce4641bd5d9af0fc263 Mon Sep 17 00:00:00 2001 From: Alexander Lowey-Weber Date: Fri, 28 Aug 2026 09:52:02 +0200 Subject: [PATCH 14/41] Add tests for tag-map. Signed-off-by: Alexander Lowey-Weber --- .../naksha/psql/ReadFeaturesByTagMapTest.kt | 253 ++++++++++++++++++ 1 file changed, 253 insertions(+) create mode 100644 here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/ReadFeaturesByTagMapTest.kt diff --git a/here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/ReadFeaturesByTagMapTest.kt b/here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/ReadFeaturesByTagMapTest.kt new file mode 100644 index 000000000..48a614d58 --- /dev/null +++ b/here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/ReadFeaturesByTagMapTest.kt @@ -0,0 +1,253 @@ +package naksha.psql + +import naksha.model.Naksha +import naksha.model.RandomFeatures +import naksha.model.TagMap +import naksha.model.objects.Index +import naksha.model.objects.Member +import naksha.model.objects.MemberType +import naksha.model.objects.NakshaCollection +import naksha.model.objects.NakshaFeature +import naksha.model.request.ReadFeatures +import naksha.model.request.SuccessResponse +import naksha.model.request.ops.And +import naksha.model.request.ops.Not +import naksha.model.request.ops.Op +import naksha.model.request.ops.Or +import naksha.model.request.ops.TagEquals +import naksha.model.request.ops.TagGt +import naksha.model.request.ops.TagGte +import naksha.model.request.ops.TagIsNull +import naksha.model.request.ops.TagLt +import naksha.model.request.ops.TagLte +import naksha.model.request.ops.TagMapHasAllOf +import naksha.model.request.ops.TagMapHasAnyOf +import naksha.model.request.ops.TagMapHasKey +import naksha.model.request.ops.TagMatches +import naksha.model.request.ops.TagStartsWith +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +private val SEARCH_TAGS_MEMBER = Member("search_tags", MemberType.TAG_MAP) + +class ReadFeaturesByTagMapTest : PgTestBase( + collection = NakshaCollection("").apply { + addMember(SEARCH_TAGS_MEMBER) + addIndex(Index("idx_search_tags", SEARCH_TAGS_MEMBER.name)) + } +) { + + @Test + fun shouldFindFeatureWithTagMapKey() { + val matching = featureWithTags("has_key" to "value") + val other = featureWithTags("other_has_key" to "value") + insertFeatures(matching, other) + + assertReturnedIds(TagMapHasKey(SEARCH_TAGS_MEMBER, "has_key"), matching.id) + assertReturnedIds(TagMapHasKey(SEARCH_TAGS_MEMBER, "missing_has_key")) + } + + @Test + fun shouldFindFeatureWithAnyTagMapKey() { + val first = featureWithTags("any_first" to true) + val second = featureWithTags("any_second" to true) + val neither = featureWithTags("any_neither" to true) + insertFeatures(first, second, neither) + + assertReturnedIds( + TagMapHasAnyOf(SEARCH_TAGS_MEMBER, "any_first", "any_second"), + first.id, + second.id, + ) + assertReturnedIds(TagMapHasAnyOf(SEARCH_TAGS_MEMBER, "missing_any_first", "missing_any_second")) + } + + @Test + fun shouldFindFeatureWithAllTagMapKeys() { + val both = featureWithTags("all_first" to 1, "all_second" to 2) + val firstOnly = featureWithTags("all_first" to 1) + val secondOnly = featureWithTags("all_second" to 2) + insertFeatures(both, firstOnly, secondOnly) + + assertReturnedIds(TagMapHasAllOf(SEARCH_TAGS_MEMBER, "all_first", "all_second"), both.id) + assertReturnedIds(TagMapHasAllOf(SEARCH_TAGS_MEMBER, "all_first", "missing_all")) + } + + @Test + fun shouldFindTagMapNullValue() { + val nullValue = featureWithTags("nullable_value" to null) + val nonNullValue = featureWithTags("nullable_value" to "value") + val missingKey = featureWithTags("other_nullable_value" to null) + insertFeatures(nullValue, nonNullValue, missingKey) + + assertReturnedIds(TagIsNull(SEARCH_TAGS_MEMBER, "nullable_value"), nullValue.id) + assertReturnedIds(TagEquals(SEARCH_TAGS_MEMBER, "nullable_value", null), nullValue.id) + } + + @Test + fun shouldFindEqualTagMapValues() { + val stringValue = featureWithTags("equals_value" to "5") + val integerValue = featureWithTags("equals_value" to 5) + val doubleValue = featureWithTags("equals_value" to 5.5) + val booleanValue = featureWithTags("equals_value" to true) + val nullValue = featureWithTags("equals_value" to null) + insertFeatures(stringValue, integerValue, doubleValue, booleanValue, nullValue) + + assertReturnedIds(TagEquals(SEARCH_TAGS_MEMBER, "equals_value", "5"), stringValue.id) + assertReturnedIds(TagEquals(SEARCH_TAGS_MEMBER, "equals_value", 5), integerValue.id) + assertReturnedIds(TagEquals(SEARCH_TAGS_MEMBER, "equals_value", 5.5), doubleValue.id) + assertReturnedIds(TagEquals(SEARCH_TAGS_MEMBER, "equals_value", true), booleanValue.id) + assertReturnedIds(TagEquals(SEARCH_TAGS_MEMBER, "equals_value", null), nullValue.id) + } + + @Test + fun shouldCompareNumericTagMapValues() { + val below = featureWithTags("numeric_value" to 4) + val equal = featureWithTags("numeric_value" to 5) + val above = featureWithTags("numeric_value" to 6) + val stringValue = featureWithTags("numeric_value" to "6") + insertFeatures(below, equal, above, stringValue) + + assertReturnedIds(TagGt(SEARCH_TAGS_MEMBER, "numeric_value", 5), above.id) + assertReturnedIds(TagGte(SEARCH_TAGS_MEMBER, "numeric_value", 5), equal.id, above.id) + assertReturnedIds(TagLt(SEARCH_TAGS_MEMBER, "numeric_value", 5), below.id) + assertReturnedIds(TagLte(SEARCH_TAGS_MEMBER, "numeric_value", 5), below.id, equal.id) + } + + @Test + fun shouldFindTagMapValueByPrefix() { + val first = featureWithTags("prefix_value" to "alpha-one") + val second = featureWithTags("prefix_value" to "alpha-two") + val other = featureWithTags("prefix_value" to "beta-one") + insertFeatures(first, second, other) + + assertReturnedIds(TagStartsWith(SEARCH_TAGS_MEMBER, "prefix_value", "alpha-"), first.id, second.id) + assertReturnedIds(TagStartsWith(SEARCH_TAGS_MEMBER, "prefix_value", "alpha-one"), first.id) + assertReturnedIds(TagStartsWith(SEARCH_TAGS_MEMBER, "prefix_value", "missing-prefix")) + } + + @Test + fun shouldFindTagMapValueByRegex() { + val first = featureWithTags("regex_value" to "alpha-123") + val second = featureWithTags("regex_value" to "alpha-abc") + val other = featureWithTags("regex_value" to "beta-123") + insertFeatures(first, second, other) + + assertReturnedIds(TagMatches(SEARCH_TAGS_MEMBER, "regex_value", "^alpha-[0-9]+$"), first.id) + assertReturnedIds(TagMatches(SEARCH_TAGS_MEMBER, "regex_value", "^missing-.*")) + } + + @Test + fun shouldNegateTagMapQueries() { + val matching = featureWithTags( + "negation_scope" to null, + "negation_key" to "match", + "negation_number" to 10, + ) + val other = featureWithTags( + "negation_scope" to null, + "negation_key" to "other", + "negation_number" to 2, + ) + val missing = featureWithTags("negation_scope" to null) + insertFeatures(matching, other, missing) + + assertReturnedIds( + And(TagMapHasKey(SEARCH_TAGS_MEMBER, "negation_scope"), Not(TagMapHasKey(SEARCH_TAGS_MEMBER, "negation_key"))), + missing.id, + ) + assertReturnedIds( + And(TagMapHasKey(SEARCH_TAGS_MEMBER, "negation_scope"), Not(TagEquals(SEARCH_TAGS_MEMBER, "negation_key", "match"))), + other.id, + missing.id, + ) + assertReturnedIds( + And(TagMapHasKey(SEARCH_TAGS_MEMBER, "negation_scope"), Not(TagGt(SEARCH_TAGS_MEMBER, "negation_number", 5))), + other.id, + missing.id, + ) + } + + @Test + fun shouldComposeTagMapQueries() { + val activeAdmin = featureWithTags( + "composition_scope" to null, + "composition_active" to true, + "composition_role" to "admin", + ) + val activeUser = featureWithTags( + "composition_scope" to null, + "composition_active" to true, + "composition_role" to "user", + ) + val inactiveAdmin = featureWithTags( + "composition_scope" to null, + "composition_active" to false, + "composition_role" to "admin", + ) + insertFeatures(activeAdmin, activeUser, inactiveAdmin) + + assertReturnedIds( + And( + TagMapHasKey(SEARCH_TAGS_MEMBER, "composition_scope"), + TagEquals(SEARCH_TAGS_MEMBER, "composition_active", true), + TagEquals(SEARCH_TAGS_MEMBER, "composition_role", "admin"), + ), + activeAdmin.id, + ) + assertReturnedIds( + And( + TagMapHasKey(SEARCH_TAGS_MEMBER, "composition_scope"), + Or( + TagEquals(SEARCH_TAGS_MEMBER, "composition_active", false), + TagEquals(SEARCH_TAGS_MEMBER, "composition_role", "user"), + ), + ), + activeUser.id, + inactiveAdmin.id, + ) + } + + @Test + fun shouldReadWrittenTagMap() { + val input = featureWithTags( + "roundtrip_marker" to null, + "roundtrip_string" to "value", + "roundtrip_boolean" to true, + "roundtrip_integer" to 42, + "roundtrip_double" to 12.5, + ) + insertFeature(input) + + val feature = executeTagMapQuery(TagMapHasKey(SEARCH_TAGS_MEMBER, "roundtrip_marker")).features.single() + assertNotNull(feature) + val tags = SEARCH_TAGS_MEMBER.readTagMap(feature) + assertNotNull(tags) + assertTrue(tags.contains("roundtrip_marker")) + assertEquals(null, tags["roundtrip_marker"]) + assertEquals("value", tags["roundtrip_string"]) + assertEquals(true, tags["roundtrip_boolean"]) + assertEquals(42L, (tags["roundtrip_integer"] as Number).toLong()) + assertEquals(12.5, (tags["roundtrip_double"] as Number).toDouble()) + } + + private fun featureWithTags(vararg tags: Pair): NakshaFeature = + RandomFeatures.randomFeature().apply { + properties[SEARCH_TAGS_MEMBER.name] = TagMap().apply { + for ((key, value) in tags) put(key, value) + } + } + + private fun executeTagMapQuery(op: Op): SuccessResponse = executeRead(ReadFeatures().apply { + catalogId = collection.catalogId + collectionId = collection.id + queryMembers = op + }) + + private fun assertReturnedIds(op: Op, vararg expectedIds: String) { + val actualIds = executeTagMapQuery(op).features.mapNotNull { it?.id }.toSet() + assertEquals(expectedIds.toSet(), actualIds) + } +} From 08b5dc801b69972986204ff29cbb714c974a1310 Mon Sep 17 00:00:00 2001 From: Alexander Lowey-Weber Date: Fri, 28 Aug 2026 09:52:33 +0200 Subject: [PATCH 15/41] Add fixes for tag-map in PgRows. Signed-off-by: Alexander Lowey-Weber --- .../commonMain/kotlin/naksha/model/Tuple.kt | 2 +- .../commonMain/kotlin/naksha/psql/PgRows.kt | 46 ++++++++++++------- 2 files changed, 31 insertions(+), 17 deletions(-) diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/Tuple.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/Tuple.kt index 21670489b..ceaf30b1e 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/Tuple.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/Tuple.kt @@ -642,7 +642,7 @@ data class Tuple @JvmOverloads constructor( * @since 3.0 * @throws NakshaException if any error occurs. */ - fun decodeFeature(globalBook: IBook?): NakshaFeature { // TODO: Java: After switching back to Java, we can allow arbitrary return types. + fun decodeFeature(globalBook: IBook?): NakshaFeature { val rawBytes = if (isGzipped(featureBytes)) gzipInflate(featureBytes) else featureBytes val decoder = JbDecoder2(globalBook, membersBook) decoder.mapBytes(rawBytes) diff --git a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgRows.kt b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgRows.kt index 3e01fe50c..79e7c56f7 100644 --- a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgRows.kt +++ b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgRows.kt @@ -9,7 +9,7 @@ import naksha.jbon.HeapBook import naksha.model.* import naksha.base.NakshaError.NakshaErrorCompanion.ILLEGAL_STATE import naksha.base.NakshaException -import naksha.base.Platform +import naksha.base.Platform.PlatformCompanion.fromJSON import naksha.base.PlatformList import naksha.base.PlatformMap import naksha.base.TupleNumber @@ -17,7 +17,12 @@ import naksha.model.objects.MemberType import naksha.base.Version import naksha.base.illegalArg import naksha.base.illegalState +import naksha.base.proxy import naksha.geo.GeoUtil +import naksha.model.objects.MemberType.MemberType_C.SPATIAL +import naksha.model.objects.MemberType.MemberType_C.TAG_LIST +import naksha.model.objects.MemberType.MemberType_C.TAG_MAP +import naksha.model.objects.MemberType.MemberType_C.TAG_MAP_FROM_ARRAY import naksha.model.objects.StandardMembers.StandardMembers_C.FeatureBytes import naksha.model.objects.StandardMembers.StandardMembers_C.Id import naksha.model.objects.StandardMembers.StandardMembers_C.NextVersion @@ -275,6 +280,7 @@ internal class PgRows { val value = getColumn(name)?.values?.get(row) if (value !is ByteArray) throw NakshaException(ILLEGAL_STATE, "The feature root is no byte-array") featureBytes = value + continue } if (member.isVirtual()) continue when (name) { @@ -293,9 +299,10 @@ internal class PgRows { else -> { val raw = getColumn(name)?.values?.get(row) val value = when (member.dataType) { - MemberType.TAG_LIST -> toAnyListOrNull(raw) - MemberType.SPATIAL -> GeoUtil.fromTWKB(raw as? ByteArray) - MemberType.TAG_MAP_FROM_ARRAY, MemberType.TAG_MAP -> when (raw) { + TAG_LIST -> toAnyListOrNull(raw) + SPATIAL -> GeoUtil.fromTWKB(raw as? ByteArray) + TAG_MAP, TAG_MAP_FROM_ARRAY -> when (raw) { + is String -> fromJSON(raw).proxy(TagMap::class) is TagMap -> raw null -> null is MapProxy<*,*> -> raw.proxy(TagMap::class) @@ -329,7 +336,7 @@ internal class PgRows { val column = getColumn(columnName) if (column != null) { setMinRows(row+1) - column.values[row] = if (MemberType.SPATIAL == column.pgColumn.memberType) GeoUtil.toTWKB(value as SpGeometry?) else value + column.values[row] = if (SPATIAL == column.pgColumn.memberType) GeoUtil.toTWKB(value as SpGeometry?) else value return true } return false @@ -345,12 +352,14 @@ internal class PgRows { val value = membersBook[memberName] column.values[row] = when (column.pgColumn.memberType) { // Convert any geometry column to TWKB, because the geometry is a bytea in Postgres, but a SpGeometry in the members-book. - MemberType.SPATIAL -> GeoUtil.toTWKB(value as SpGeometry?) - MemberType.TAG_MAP_FROM_ARRAY, MemberType.TAG_MAP -> when (value) { + SPATIAL -> GeoUtil.toTWKB(value as SpGeometry?) + TAG_MAP_FROM_ARRAY -> when (value) { null -> null - is TagMap -> Platform.toJSON(value) - is PlatformList -> Platform.toJSON(value.proxy(TagList::class).toTagMap()) - else -> throw illegalArg("Cannot convert value of type ${value.let { it::class.simpleName } ?: "null"} to TagMap") + is TagList -> value.toTagMap() + is ListProxy<*> -> value.proxy(TagList::class).toTagMap() + is TagMap -> value + is PlatformList -> value.proxy(TagList::class).toTagMap() + else -> throw illegalArg("Cannot convert value of type ${value?.let { it::class.simpleName } ?: "null"} to TagMap") } else -> value } @@ -528,16 +537,21 @@ internal class PgRows { fun typeNames(): Array = Array(columns.size) { val col = columns[it].pgColumn // A text[] column can't ride the batch UNNEST (would be text[][]); carry it as jsonb, converted back in newRowProjection(). - if (col.memberType == MemberType.TAG_LIST) PgType.JSONB.text + "[]" + if (col.memberType == TAG_LIST) PgType.JSONB.text + "[]" else col.pgType.text + "[]" } fun newRowProjection(): String = columns.joinToString(", ") { val ident = PgUtil.quoteIdent(it.alias) - if (it.pgColumn.memberType == MemberType.TAG_LIST) - "CASE WHEN $ident IS NULL THEN NULL ELSE ARRAY(SELECT json_array_elements_text($ident::json)) END AS $ident" - else - ident + when (it.pgColumn.memberType) { + TAG_LIST -> { + "CASE WHEN $ident IS NULL THEN NULL ELSE ARRAY(SELECT json_array_elements_text($ident::json)) END AS $ident" + } + TAG_MAP, TAG_MAP_FROM_ARRAY -> { + "$ident::jsonb" + } + else -> ident + } } /** @@ -559,4 +573,4 @@ internal class PgRows { */ @Suppress("UNCHECKED_CAST") fun values(): Array = Array(columns.size) { columns[it].anyArray() } as Array -} \ No newline at end of file +} From 57f054627cce7b7e0ea2378935c532adb7b24f4d Mon Sep 17 00:00:00 2001 From: Alexander Lowey-Weber Date: Mon, 31 Aug 2026 09:25:28 +0200 Subject: [PATCH 16/41] Improve documentation Signed-off-by: Alexander Lowey-Weber --- .../commonMain/kotlin/naksha/base/LibBase.kt | 3 +- .../commonMain/kotlin/naksha/jbon/IBook.kt | 31 +++++++++---- .../kotlin/naksha/jbon/Jbon2MembersTest.kt | 12 ++--- .../commonMain/kotlin/naksha/model/Naksha.kt | 45 +------------------ .../kotlin/naksha/model/MemberTest.kt | 28 +----------- 5 files changed, 32 insertions(+), 87 deletions(-) diff --git a/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/LibBase.kt b/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/LibBase.kt index f1380154a..e9fbe4db2 100644 --- a/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/LibBase.kt +++ b/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/LibBase.kt @@ -80,9 +80,10 @@ inline fun WeakRef(referee: T): WeakRef = Platform.newWeakRef(refer * @return this as the requested proxy or `null`. * @since 3.0 */ +@Suppress("UNCHECKED_CAST") inline fun Any?.proxy(klass: KClass): T? { if (this == null) return null - if (klass.isInstance(this)) return klass.cast(this) + if (klass.isInstance(this)) return this as T if (this is PlatformMap) return this.proxy(klass) if (this is Proxy) return this.proxy(klass) return null diff --git a/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/IBook.kt b/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/IBook.kt index 7cdc414ad..d3251dc92 100644 --- a/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/IBook.kt +++ b/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/IBook.kt @@ -7,15 +7,28 @@ import kotlin.js.JsExport import kotlin.js.JsName /** - * An interface to be implemented by all books. Books can contain a combination of the following types, and only of these: - * - `null` - * - `Boolean` - * - `Int` - * - `Int64` - * - `Double` - * - `String` - * - `Map` - with _Any_ again being limited to these types. - * - `List` - with _Any_ again being limited to these types. + * An interface to be implemented by all `JBON` books. + * + * Books contain `JBON` units that can be referred to from a `JBON` binary. A `unit` in `JBON` is basically any defined value, please refer to the `JBON` specication. The purpose of books is deduplication and relocation of units. There are generally four type of books: + * - `local` - embedded into a binary encoded `JBON`, small local compression. + * - `global` - shared between applications and storages, strong compression factor. + * - `member` - use to relocate units into dedicated places for indexing and searching. + * - `const` - fixed constant units that encoder and decoder need to know. + * + * All books have two sections: strings and values. Even while values can be all units, except for strings, encoding primities does not make much sense, because it will rarly save any space. Generall the content are `JBON` structures, so one of the following: + * - `JbonArray` - An array of arbitrary units. + * - `JbonMap` - A map where the key can be any primitive, the value can be any unit. + * - `JbonTagList` - A list of strings with some special encoding. + * - `JbonObject` - A map where the key is a string literal and the value can be any unit. + * - `JbonTagMap` - A map where the key is a string literal and the value can only be a primitive. + * - `JbonDictionary` - A map where the key is a string literal and the value is a string. + * - `JbonSpatial` - A byte-array that encodes an geometry encoded as [TWKB](https://github.com/TWKB/Specification/blob/master/twkb.md). + * - `JbonBytes` - A byte-array with arbitrary content. + * - `JbonBinary` - An byte-array with metadata about the content, optionally compressed by well known algorithms. + * + * All objects can be represented in `JSON` or `XML`, but only `JbonArray` and `JbonObject` are natural raw `JSON` entities. All others are custom extension to be used in Naksha context. + * + * Beware, the books represented by this interface contain these _HEAP_ representations of the data. So [IBook] represents a decoded `JBON` book. There is as well a binary representation as [ByteArray] that can be read using the `JbonDecoder` and that can be generated using the `JbonEncoder`. Storages need to support both formats, the binary [ByteArray] representation and the decoded _HEAP_ representation through [IBook]. * @since 3.0.0 * @see JbDictionary */ diff --git a/here-naksha-lib-jbon/src/jvmTest/kotlin/naksha/jbon/Jbon2MembersTest.kt b/here-naksha-lib-jbon/src/jvmTest/kotlin/naksha/jbon/Jbon2MembersTest.kt index 0820a9e54..02d4f7dd1 100644 --- a/here-naksha-lib-jbon/src/jvmTest/kotlin/naksha/jbon/Jbon2MembersTest.kt +++ b/here-naksha-lib-jbon/src/jvmTest/kotlin/naksha/jbon/Jbon2MembersTest.kt @@ -50,7 +50,7 @@ class Jbon2MembersTest { val bin = Binary() bin.view = Platform.newDataView(bytes) bin.end = bytes.size - val dec = JbDecoder2(membersDict = membersDict) + val dec = JbDecoder2(membersBook = membersDict) dec.view = bin dec.end = bytes.size return dec.decodeValueAt(0) @@ -61,7 +61,7 @@ class Jbon2MembersTest { val enc = JbEncoder2() @Suppress("UNCHECKED_CAST") val tupleBytes = enc.buildTupleFromMap(feature as MapProxy) - val dec = JbDecoder2(membersDict = membersDict) + val dec = JbDecoder2(membersBook = membersDict) dec.mapBytes(tupleBytes) return dec.toAnyObject() } @@ -92,7 +92,7 @@ class Jbon2MembersTest { // Members book: slot 0 → 42 val membersDict = ListDict(listOf(42)) - val dec = JbDecoder2(membersDict = membersDict) + val dec = JbDecoder2(membersBook = membersDict) dec.mapBytes(tupleBytes) val decoded = dec.toAnyObject() @@ -131,7 +131,7 @@ class Jbon2MembersTest { // Members book: slot 0 → raw TWKB ByteArray (simulating PostgreSQL bytea column) val membersDict = ListDict(listOf(SpPoint(lon, lat))) - val dec = JbDecoder2(membersDict = membersDict) + val dec = JbDecoder2(membersBook = membersDict) dec.mapBytes(tupleBytes) val decoded = dec.toAnyObject() @@ -204,7 +204,7 @@ class Jbon2MembersTest { val membersDict = ListDict(listOf("hello world")) - val dec = JbDecoder2(membersDict = membersDict) + val dec = JbDecoder2(membersBook = membersDict) dec.mapBytes(tupleBytes) val decoded = dec.toAnyObject() @@ -232,7 +232,7 @@ class Jbon2MembersTest { val membersDict = ListDict(listOf(null)) - val dec = JbDecoder2(membersDict = membersDict) + val dec = JbDecoder2(membersBook = membersDict) dec.mapBytes(tupleBytes) val decoded = dec.toAnyObject() diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/Naksha.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/Naksha.kt index c1990be9c..6b4c5612b 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/Naksha.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/Naksha.kt @@ -5,7 +5,6 @@ package naksha.model import naksha.base.* import naksha.base.Platform.PlatformCompanion.fromJSON import naksha.base.Platform.PlatformCompanion.md5 -import naksha.base.Platform.PlatformCompanion.toJSON import naksha.geo.GeoUtil.GeoUtil_C.fromTWKB import naksha.geo.GeoUtil.GeoUtil_C.toTWKB import naksha.geo.SpGeometry @@ -415,55 +414,13 @@ class Naksha private constructor() { @JvmStatic fun alternativeInt32(number: Int): Int = (number + 1) or -2147483648 - /** - * Decode Naksha tags from their binary representation. - * @param bytes the bytes to decode. - * @param dictReader the dictionary manager to use for decoding; if any. - * @return the Naksha tags. - * @since 3.0 - */ - @JsStatic - @JvmStatic - fun decodeTags(json: String?): TagMap? { - if (json.isNullOrBlank()) return null - val decoded = fromJSON(json) - return if (decoded is PlatformMap) decoded.proxy(TagMap::class) else null - } - - /** - * Encodes the given tags into their binary representation. - * @param tags the tags to encode. - * @return the JSON text representation, or _null_ if [tags] is _null_ / empty. - * @since 3.0 - */ - @JsStatic - @JvmStatic - fun encodeTags(tags: TagMap?): String? { - if (tags.isNullOrEmpty()) return null - return toJSON(tags) - } - - /** - * Encodes the given tag-list into the [tag_list][naksha.model.objects.MemberType.TAG_LIST] - * representation: a JSON array, with the element order preserved. - * @param tags the tags to encode. - * @return the JSON array text representation, or _null_ if [tags] is _null_ / empty. - * @since 3.0 - */ - @JsStatic - @JvmStatic - fun encodeTagList(tags: TagList?): String? { - if (tags.isNullOrEmpty()) return null - return toJSON(tags) - } - /** * Decodes Naksha tags from their JSON text representation into a [TagList]. * * Supports both persisted forms: * - a JSON array ([tag_list][naksha.model.objects.MemberType.TAG_LIST], the default) is returned * unmodified, preserving the element order; - * - a JSON object ([naksha.model.objects.MemberType.TAG_MAP_FROM_ARRAY]) is re-flattened via + * - a JSON object ([naksha.model.objects.MemberType.TAG_MAP_FROM_TAG_LIST]) is re-flattened via * [TagMap.toTagList], in which case the original order is not guaranteed. * @param json the JSON text to decode (value of the `tags` member). * @return the decoded tag-list, or _null_ if [json] is _null_, blank, or neither an array nor an object. diff --git a/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/MemberTest.kt b/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/MemberTest.kt index c73fc5e42..40376a4d5 100644 --- a/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/MemberTest.kt +++ b/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/MemberTest.kt @@ -93,7 +93,7 @@ class MemberTest { assertNotNull(MemberType.BYTE_ARRAY) // Virtual / jsonb. assertNotNull(MemberType.TAG_MAP) - assertNotNull(MemberType.TAG_MAP_FROM_ARRAY) + assertNotNull(MemberType.TAG_MAP_FROM_TAG_LIST) assertNotNull(MemberType.TAG_LIST) } @@ -102,30 +102,4 @@ class MemberTest { assertEquals(MemberType.TAG_LIST, naksha.model.objects.XyzMembers.XyzTags.dataType) assertNotNull(naksha.model.objects.XyzIndices.XyzTags) } - - @Test - fun tagListEncodesAsJsonArrayPreservingOrder() { - val tags = TagList("foo", "bar", "a=b") - val json = Naksha.encodeTagList(tags) - assertNotNull(json) - // Round-trip must preserve the exact element order (set guarantee). - val decoded = Naksha.decodeTagList(json) - assertNotNull(decoded) - assertEquals(listOf("foo", "bar", "a=b"), decoded.filterNotNull()) - } - - @Test - fun decodeTagListSupportsLegacyMapForm() { - // TAGS_FROM_ARRAY persists a JSON object; decodeTagList must re-flatten it. - val decoded = Naksha.decodeTagList("""{"foo":null,"a":"b","n":5.0}""") - assertNotNull(decoded) - val elements = decoded.filterNotNull().toSet() - assertEquals(setOf("foo", "a=b", "n:=5.0"), elements) - } - - @Test - fun encodeTagListOfEmptyIsNull() { - assertEquals(null, Naksha.encodeTagList(null)) - assertEquals(null, Naksha.encodeTagList(TagList())) - } } From 2321a830a31c4e3e366dbc8fe25448f935ed81b9 Mon Sep 17 00:00:00 2001 From: Alexander Lowey-Weber Date: Mon, 31 Aug 2026 09:26:31 +0200 Subject: [PATCH 17/41] Move toArray helpers from AnyList into ListProxy so they are available for all lists. Signed-off-by: Alexander Lowey-Weber --- .../commonMain/kotlin/naksha/base/AnyList.kt | 228 ------------------ .../kotlin/naksha/base/ListProxy.kt | 228 ++++++++++++++++++ 2 files changed, 228 insertions(+), 228 deletions(-) diff --git a/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/AnyList.kt b/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/AnyList.kt index 010b1a741..d4f06124f 100644 --- a/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/AnyList.kt +++ b/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/AnyList.kt @@ -2,7 +2,6 @@ package naksha.base -import naksha.base.Platform.PlatformCompanion.toJSON import kotlin.js.JsExport /** @@ -23,231 +22,4 @@ open class AnyList : ListProxy(Any::class) { super.add(element) return this } - - /** - * Convert this list into an integer-array. - * @param convertNonBoolean if _true_ all elements not being [Boolean] are converted into boolean; otherwise an exception is thrown. - * @return this list as [BooleanArray]. - * @throws NakshaException with error [ILLEGAL_STATE][NakshaError.ILLEGAL_STATE] if `convertNonBoolean` is _false_ and an element is no boolean. - * @since 3.0 - */ - fun toBooleanArray(convertNonBoolean: Boolean): BooleanArray { - val array = BooleanArray(size) - var end = 0 - for (i in 0 until size) { - val item = get(i) - if (item is Boolean) { - array[end++] = item - } else if (convertNonBoolean) { - array[end++] = when (item) { - is String -> "true".equals(item, ignoreCase = true) - is Float -> item != 0.0f - is Double -> item != 0.0 - is Number -> item.toLong() != 0L - else -> false - } - } else throw illegalState("The element at index $i is no boolean") - } - return if (end == array.size) array else array.copyOf(end) - } - - /** - * Convert this list into an short-array. - * @param ignoreIllegalValues if _true_ invalid elements, `null` elements, or elements not being in the valid short range are ignored; otherwise an exception is thrown. - * @return this list as [ShortArray]. - * @throws NakshaException with error [ILLEGAL_STATE][NakshaError.ILLEGAL_STATE] if `ignoreIllegalValues` is _false_ and an element is no 16-bit integer, this includes integers being out of the valid 16-bit range _(so being too small or large)_. - * @since 3.0 - */ - fun toShortArray(ignoreIllegalValues: Boolean): ShortArray { - val array = ShortArray(size) - var end = 0 - for (i in 0 until size) { - val item = get(i) - if (item is Number) { - val value = item.toLong() - if (value in Short.MIN_VALUE.toLong() .. Short.MAX_VALUE.toLong()) { - array[end++] = value.toShort() - continue - } - } - if (!ignoreIllegalValues) { - throw illegalState("The element at index $i is no valid short") - } - } - return if (end == array.size) array else array.copyOf(end) - } - - /** - * Convert this list into an integer-array. - * @param ignoreIllegalValues if _true_ invalid elements, `null` elements, or elements not being in the valid integer range are ignored; otherwise an exception is thrown. - * @return this list as [IntArray]. - * @throws NakshaException with error [ILLEGAL_STATE][NakshaError.ILLEGAL_STATE] if `ignoreIllegalValues` is _false_ and an element is no 32-bit integer, this includes integers being out of the valid 32-bit range _(so being too small or large)_. - * @since 3.0 - */ - fun toIntArray(ignoreIllegalValues: Boolean): IntArray { - val array = IntArray(size) - var end = 0 - for (i in 0 until size) { - val item = get(i) - if (item is Number) { - val value = item.toLong() - if (value in Int.MIN_VALUE.toLong() .. Int.MAX_VALUE.toLong()) { - array[end++] = value.toInt() - continue - } - } - if (!ignoreIllegalValues) { - throw illegalState("The element at index $i is no valid integer") - } - } - return if (end == array.size) array else array.copyOf(end) - } - - /** - * Convert this list into an integer-array. - * @param ignoreIllegalValues if _true_ invalid elements, `null` elements, or elements not being in the valid integer range are ignored; otherwise an exception is thrown. - * @return this list as [LongArray]. - * @throws NakshaException with error [ILLEGAL_STATE][NakshaError.ILLEGAL_STATE] if `ignoreIllegalValues` is _false_ and an elements is no 64-bit integer. - * @since 3.0 - */ - fun toLongArray(ignoreIllegalValues: Boolean): LongArray { - val array = LongArray(size) - var end = 0 - for (i in 0 until size) { - val item = get(i) - if (item is Number) { - array[end++] = item.toLong() - continue - } - if (!ignoreIllegalValues) { - throw illegalState("The element at index $i is no valid long") - } - } - return if (end == array.size) array else array.copyOf(end) - } - - /** - * Convert this list into a float-array. - * @param ignoreIllegalValues if _true_ invalid elements, `null` elements are ignored; otherwise an exception is thrown. - * @return this list as [DoubleArray]. - * @throws NakshaException with error [ILLEGAL_STATE][NakshaError.ILLEGAL_STATE] if `ignoreIllegalValues` is _false_ and an elements is no number. - * @since 3.0 - */ - fun toFloatArray(ignoreIllegalValues: Boolean): FloatArray { - val array = FloatArray(size) - var end = 0 - for (i in 0 until size) { - val item = get(i) - if (item is Number) { - array[end++] = item.toFloat() - continue - } - if (!ignoreIllegalValues) { - throw illegalState("The element at index $i is no valid number") - } - } - return if (end == array.size) array else array.copyOf(end) - } - - /** - * Convert this list into a double-array. - * @param ignoreIllegalValues if _true_ invalid elements, `null` elements are ignored; otherwise an exception is thrown. - * @return this list as [DoubleArray]. - * @throws NakshaException with error [ILLEGAL_STATE][NakshaError.ILLEGAL_STATE] if `ignoreIllegalValues` is _false_ and an elements is no number. - * @since 3.0 - */ - fun toDoubleArray(ignoreIllegalValues: Boolean): DoubleArray { - val array = DoubleArray(size) - var end = 0 - for (i in 0 until size) { - val item = get(i) - if (item is Number) { - array[end++] = item.toDouble() - continue - } - if (!ignoreIllegalValues) { - throw illegalState("The element at index $i is no valid number") - } - } - return if (end == array.size) array else array.copyOf(end) - } - - /** - * Convert this list into an array of [ByteArray]. - * @param ignoreIllegalValues if _true_ elements not being a [ByteArray] are ignored; otherwise an exception is thrown. - * @return this list as array of strings. - * @throws NakshaException with error [ILLEGAL_STATE][NakshaError.ILLEGAL_STATE] if `ignoreIllegalValues` is _false_ and an element is no [ByteArray]. - * @since 3.0 - */ - fun toByteArrayArray(ignoreIllegalValues: Boolean): Array { - val array = arrayOfNulls(size) - var end = 0 - for (i in 0 until size) { - val item = get(i) - if (item is ByteArray) { - array[end++] = item - continue - } - if (!ignoreIllegalValues) { - throw illegalState("The element at index $i is no valid string") - } - } - @Suppress("UNCHECKED_CAST") - return (if (end == array.size) array else array.copyOf(end)) as Array - } - - /** - * Convert this list into a string-array. - * @param ignoreIllegalValues if _true_ elements not being string are ignored; otherwise an exception is thrown. - * @return this list as array of strings. - * @throws NakshaException with error [ILLEGAL_STATE][NakshaError.ILLEGAL_STATE] if `ignoreIllegalValues` is _false_ and an element is no string. - * @since 3.0 - */ - fun toStringArray(ignoreIllegalValues: Boolean): Array { - val array = arrayOfNulls(size) - var end = 0 - for (i in 0 until size) { - val item = get(i) - if (item is String) { - array[end++] = item - continue - } - if (!ignoreIllegalValues) { - throw illegalState("The element at index $i is no valid string") - } - } - @Suppress("UNCHECKED_CAST") - return (if (end == array.size) array else array.copyOf(end)) as Array - } - - /** - * Convert this list into a string-array. - * @param invalidToNull if _true_ invalid elements are turned into `null` values. - * @param ignoreIllegalValues if `invalidToNull` is _false_ and this argument is _true_, invalid elements are ignored _(be removed from the returned list)_; otherwise an exception is thrown for invalid elements. - * @return this list as array of strings, may contain `null` values. - * @throws NakshaException with error [ILLEGAL_STATE][NakshaError.ILLEGAL_STATE] if `ignoreIllegalValues` is _false_ and an element is neither `null` nor a string. - * @since 3.0 - */ - fun toStringNullableArray(invalidToNull: Boolean, ignoreIllegalValues: Boolean): Array { - val array = arrayOfNulls(size) - var end = 0 - for (i in 0 until size) { - var item = get(i) - if (item != null && item !is String) { - if (invalidToNull) item = null - else if (ignoreIllegalValues) continue - else throw illegalState("The element at index $i is no valid string") - } - array[end++] = item - } - return if (end == array.size) array else array.copyOf(end) - } - - /** - * Convert this list into a string-array that contains all elements `JSON` serialized. - * @return this list as a string-array of `JSON` serialized elements. - * @since 3.0 - */ - fun toJsonArray(): Array = Array(size) { toJSON(it) } - } diff --git a/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/ListProxy.kt b/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/ListProxy.kt index 2e1c70689..649ab850b 100644 --- a/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/ListProxy.kt +++ b/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/ListProxy.kt @@ -2,6 +2,7 @@ package naksha.base +import naksha.base.Platform.PlatformCompanion.toJSON import naksha.base.PlatformListApi.PlatformListApiCompanion.array_delete import naksha.base.PlatformListApi.PlatformListApiCompanion.array_entries import naksha.base.PlatformListApi.PlatformListApiCompanion.array_get @@ -284,6 +285,233 @@ open class ListProxy(private var _elementKlass: KClass) : Proxy( return (if (a == array.size) array else array.copyOf(a)) as Array } + + /** + * Convert this list into an integer-array. + * @param convertNonBoolean if _true_, then all elements not being [Boolean] are converted into boolean; otherwise an exception is thrown. + * @return this list as [BooleanArray]. + * @throws NakshaException with error [ILLEGAL_STATE][NakshaError.ILLEGAL_STATE] if `convertNonBoolean` is _false_ and an element is no boolean. + * @since 3.0 + */ + fun toBooleanArray(convertNonBoolean: Boolean): BooleanArray { + val array = BooleanArray(size) + var end = 0 + for (i in 0 until size) { + val item = get(i) + if (item is Boolean) { + array[end++] = item + } else if (convertNonBoolean) { + array[end++] = when (item) { + is String -> "true".equals(item, ignoreCase = true) + is Float -> item != 0.0f + is Double -> item != 0.0 + is Number -> item.toLong() != 0L + else -> false + } + } else throw illegalState("The element at index $i is no boolean") + } + return if (end == array.size) array else array.copyOf(end) + } + + /** + * Convert this list into a short-array. + * @param ignoreIllegalValues if _true_, then invalid elements, `null` elements, or elements not being in the valid short range are ignored; otherwise an exception is thrown. + * @return this list as [ShortArray]. + * @throws NakshaException with error [ILLEGAL_STATE][NakshaError.ILLEGAL_STATE] if `ignoreIllegalValues` is _false_ and an element is no 16-bit integer, this includes integers being out of the valid 16-bit range _(so being too small or large)_. + * @since 3.0 + */ + fun toShortArray(ignoreIllegalValues: Boolean): ShortArray { + val array = ShortArray(size) + var end = 0 + for (i in 0 until size) { + val item = get(i) + if (item is Number) { + val value = item.toLong() + if (value in Short.MIN_VALUE.toLong() .. Short.MAX_VALUE.toLong()) { + array[end++] = value.toShort() + continue + } + } + if (!ignoreIllegalValues) { + throw illegalState("The element at index $i is no valid short") + } + } + return if (end == array.size) array else array.copyOf(end) + } + + /** + * Convert this list into an integer-array. + * @param ignoreIllegalValues if _true_, then invalid elements, `null` elements, or elements not being in the valid integer range are ignored; otherwise an exception is thrown. + * @return this list as [IntArray]. + * @throws NakshaException with error [ILLEGAL_STATE][NakshaError.ILLEGAL_STATE] if `ignoreIllegalValues` is _false_ and an element is no 32-bit integer, this includes integers being out of the valid 32-bit range _(so being too small or large)_. + * @since 3.0 + */ + fun toIntArray(ignoreIllegalValues: Boolean): IntArray { + val array = IntArray(size) + var end = 0 + for (i in 0 until size) { + val item = get(i) + if (item is Number) { + val value = item.toLong() + if (value in Int.MIN_VALUE.toLong() .. Int.MAX_VALUE.toLong()) { + array[end++] = value.toInt() + continue + } + } + if (!ignoreIllegalValues) { + throw illegalState("The element at index $i is no valid integer") + } + } + return if (end == array.size) array else array.copyOf(end) + } + + /** + * Convert this list into an integer-array. + * @param ignoreIllegalValues if _true_, then invalid elements, `null` elements, or elements not being in the valid integer range are ignored; otherwise an exception is thrown. + * @return this list as [LongArray]. + * @throws NakshaException with error [ILLEGAL_STATE][NakshaError.ILLEGAL_STATE] if `ignoreIllegalValues` is _false_ and an elements is no 64-bit integer. + * @since 3.0 + */ + fun toLongArray(ignoreIllegalValues: Boolean): LongArray { + val array = LongArray(size) + var end = 0 + for (i in 0 until size) { + val item = get(i) + if (item is Number) { + array[end++] = item.toLong() + continue + } + if (!ignoreIllegalValues) { + throw illegalState("The element at index $i is no valid long") + } + } + return if (end == array.size) array else array.copyOf(end) + } + + /** + * Convert this list into a float-array. + * @param ignoreIllegalValues if _true_, then invalid elements, `null` elements are ignored; otherwise an exception is thrown. + * @return this list as [DoubleArray]. + * @throws NakshaException with error [ILLEGAL_STATE][NakshaError.ILLEGAL_STATE] if `ignoreIllegalValues` is _false_ and an elements is no number. + * @since 3.0 + */ + fun toFloatArray(ignoreIllegalValues: Boolean): FloatArray { + val array = FloatArray(size) + var end = 0 + for (i in 0 until size) { + val item = get(i) + if (item is Number) { + array[end++] = item.toFloat() + continue + } + if (!ignoreIllegalValues) { + throw illegalState("The element at index $i is no valid number") + } + } + return if (end == array.size) array else array.copyOf(end) + } + + /** + * Convert this list into a double-array. + * @param ignoreIllegalValues if _true_, then invalid elements, `null` elements are ignored; otherwise an exception is thrown. + * @return this list as [DoubleArray]. + * @throws NakshaException with error [ILLEGAL_STATE][NakshaError.ILLEGAL_STATE] if `ignoreIllegalValues` is _false_ and an elements is no number. + * @since 3.0 + */ + fun toDoubleArray(ignoreIllegalValues: Boolean): DoubleArray { + val array = DoubleArray(size) + var end = 0 + for (i in 0 until size) { + val item = get(i) + if (item is Number) { + array[end++] = item.toDouble() + continue + } + if (!ignoreIllegalValues) { + throw illegalState("The element at index $i is no valid number") + } + } + return if (end == array.size) array else array.copyOf(end) + } + + /** + * Convert this list into an array of [ByteArray]. + * @param ignoreIllegalValues if _true_, then elements not being a [ByteArray] are ignored; otherwise an exception is thrown. + * @return this list as array of strings. + * @throws NakshaException with error [ILLEGAL_STATE][NakshaError.ILLEGAL_STATE] if `ignoreIllegalValues` is _false_ and an element is no [ByteArray]. + * @since 3.0 + */ + fun toByteArrayArray(ignoreIllegalValues: Boolean): Array { + val array = arrayOfNulls(size) + var end = 0 + for (i in 0 until size) { + val item = get(i) + if (item is ByteArray) { + array[end++] = item + continue + } + if (!ignoreIllegalValues) { + throw illegalState("The element at index $i is no valid string") + } + } + @Suppress("UNCHECKED_CAST") + return (if (end == array.size) array else array.copyOf(end)) as Array + } + + /** + * Convert this list into a string-array. + * @param ignoreIllegalValues if _true_, then elements not being string are ignored; otherwise an exception is thrown. + * @return this list as array of strings. + * @throws NakshaException with error [ILLEGAL_STATE][NakshaError.ILLEGAL_STATE] if `ignoreIllegalValues` is _false_ and an element is no string. + * @since 3.0 + */ + fun toStringArray(ignoreIllegalValues: Boolean): Array { + val array = arrayOfNulls(size) + var end = 0 + for (i in 0 until size) { + val item = get(i) + if (item is String) { + array[end++] = item + continue + } + if (!ignoreIllegalValues) { + throw illegalState("The element at index $i is no valid string") + } + } + @Suppress("UNCHECKED_CAST") + return (if (end == array.size) array else array.copyOf(end)) as Array + } + + /** + * Convert this list into a string-array. + * @param invalidToNull if _true_, then invalid elements are turned into `null` values. + * @param ignoreIllegalValues if `invalidToNull` is _false_ and this argument is _true_, invalid elements are ignored _(be removed from the returned list)_; otherwise an exception is thrown for invalid elements. + * @return this list as array of strings, may contain `null` values. + * @throws NakshaException with error [ILLEGAL_STATE][NakshaError.ILLEGAL_STATE] if `ignoreIllegalValues` is _false_ and an element is neither `null` nor a string. + * @since 3.0 + */ + fun toStringNullableArray(invalidToNull: Boolean, ignoreIllegalValues: Boolean): Array { + val array = arrayOfNulls(size) + var end = 0 + for (i in 0 until size) { + var item = get(i) + if (item != null && item !is String) { + if (invalidToNull) item = null + else if (ignoreIllegalValues) continue + else throw illegalState("The element at index $i is no valid string") + } + array[end++] = item + } + return if (end == array.size) array else array.copyOf(end) + } + + /** + * Convert this list into a string-array that contains all elements `JSON` serialized. + * @return this list as a string-array of `JSON` serialized elements. + * @since 3.0 + */ + fun toJsonArray(): Array = Array(size) { toJSON(it) } + class ListProxyIterator( private val basicIterator: MutableListIterator, private val owner: ListProxy From 1f5e1db114058988663dd59f401bd26c0e84cc3e Mon Sep 17 00:00:00 2001 From: Alexander Lowey-Weber Date: Mon, 31 Aug 2026 09:27:13 +0200 Subject: [PATCH 18/41] Rename dict to book, minor performance improvement to avoid data copy for strings section in books. Signed-off-by: Alexander Lowey-Weber --- .../kotlin/naksha/jbon/JbDecoder2.kt | 56 +++++-------------- 1 file changed, 13 insertions(+), 43 deletions(-) diff --git a/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/JbDecoder2.kt b/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/JbDecoder2.kt index a2545961d..fa22da436 100644 --- a/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/JbDecoder2.kt +++ b/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/JbDecoder2.kt @@ -19,17 +19,17 @@ import kotlin.jvm.JvmStatic * The decoder maps a single top-level unit. To decode a stored tuple, call [mapBytes] which will * skip the file header (if present), descend into the [Tuple], and expose the feature [Object]. * - * @property globalDict The global book used to resolve global references; if any. - * @property membersDict The members book used to resolve member references ([JB2_REF_BOOK_MEMBERS]); + * @property globalBook The global book used to resolve global references; if any. + * @property membersBook The members book used to resolve member references ([JB2_REF_BOOK_MEMBERS]); * if any. Entries are arbitrary `Any?` values assembled by the caller (e.g. from database columns). * If an entry is a [ByteArray] it is interpreted as raw TWKB bytes and converted to [SpGeometry] * via [GeoUtil.fromTWKB] before being returned to the caller. * Embedded members books inside a [Tuple] are **not** loaded automatically; the caller must - * supply [membersDict] explicitly before decoding. + * supply [membersBook] explicitly before decoding. */ @Suppress("MemberVisibilityCanBePrivate", "OPT_IN_USAGE", "DuplicatedCode") @JsExport -open class JbDecoder2(var globalDict: IBook? = null, var membersDict: IBook? = null) { +open class JbDecoder2(var globalBook: IBook? = null, var membersBook: IBook? = null) { /** The underlying binary view. */ var view: BinaryView = Binary() @@ -103,9 +103,9 @@ open class JbDecoder2(var globalDict: IBook? = null, var membersDict: IBook? = n offset: Int, end: Int, sb: StringBuilder, - globalStrings: List? = null, + globalBook: IBook? = null, localStrings: List? = null, - memberStrings: List? = null + memberBook: IBook? = null ) { var i = offset while (i < end) { @@ -123,13 +123,12 @@ open class JbDecoder2(var globalDict: IBook? = null, var membersDict: IBook? = n i += 4 } val bb = (lead and JB2_SREF_BOOK_MASK) ushr JB2_SREF_BOOK_SHIFT - val strings = when (bb) { - JB2_BOOK_GLOBAL -> globalStrings - JB2_BOOK_LOCAL -> localStrings - JB2_BOOK_MEMBERS -> memberStrings + val s = when (bb) { + JB2_BOOK_GLOBAL -> globalBook?.getStringAt(index) + JB2_BOOK_LOCAL -> localStrings?.get(index) + JB2_BOOK_MEMBERS -> memberBook?.getStringAt(index) else -> null // const book holds no addressable strings here } - val s = strings?.getOrNull(index) if (s != null) sb.append(s) val add = (lead and JB2_SREF_ADD_MASK) ushr JB2_SREF_ADD_SHIFT val ch = JB2_ADD_CHAR[add] @@ -305,9 +304,9 @@ open class JbDecoder2(var globalDict: IBook? = null, var membersDict: IBook? = n else -> view.getInt32(at + 1) } return when (lead and JB2_REF_BOOK_MASK) { - JB2_REF_BOOK_GLOBAL -> globalDict?.get(index) + JB2_REF_BOOK_GLOBAL -> globalBook?.get(index) JB2_REF_BOOK_LOCAL -> localStrings?.getOrNull(index) - JB2_REF_BOOK_MEMBERS -> resolveMembersRef(index) + JB2_REF_BOOK_MEMBERS -> membersBook?.get(index) else -> null // const } } @@ -316,39 +315,10 @@ open class JbDecoder2(var globalDict: IBook? = null, var membersDict: IBook? = n val hs = stringHeaderSize(at) val total = stringUnitSize(at) val sb = StringBuilder() - readSubstring(view, at + hs, at + total, sb, globalStringsList(), localStrings, memberStringsList()) + readSubstring(view, at + hs, at + total, sb, globalBook, localStrings, membersBook) return sb.toString() } - private fun globalStringsList(): List? { - val g = globalDict ?: return null - // Materialise lazily via IBook.get is expensive; only used for sref resolution. Build once. - val len = g.length - return List(len) { g.get(it)?.toString() ?: "" } - } - - /** - * Materialise the members book as a flat string list for use inside string-reference resolution. - * Members are plain values stored in PostgreSQL columns (text, int, etc.) — no nested references. - * Non-string entries are converted via [toString]; null entries become empty strings. - */ - private fun memberStringsList(): List? { - val m = membersDict ?: return null - val len = m.length - return List(len) { m.get(it)?.toString() ?: "" } - } - - /** - * Resolve a [JB2_REF_BOOK_MEMBERS] reference at the given [index]. - * - * The entry is retrieved from [membersDict]. If the returned value is a [ByteArray] it is - * treated as raw TWKB bytes and converted to [SpGeometry] via [GeoUtil.fromTWKB]. All other - * types are returned as-is. - */ - private fun resolveMembersRef(index: Int): Any? { - val value = membersDict?.get(index) ?: return null - return value - } private fun decodeStructAt(at: Int): Any? { val type = leadIn(at) and JB2_STRUCT_TYPE_MASK From 6d286e0f6012ddaf66d54d06bccc7c4ff9381360 Mon Sep 17 00:00:00 2001 From: Alexander Lowey-Weber Date: Mon, 31 Aug 2026 09:28:04 +0200 Subject: [PATCH 19/41] Improve static fromArray helper. Signed-off-by: Alexander Lowey-Weber --- .../commonMain/kotlin/naksha/model/TagList.kt | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TagList.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TagList.kt index c2248f001..75750641f 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TagList.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TagList.kt @@ -8,6 +8,7 @@ import naksha.model.TagNormalizer.TagNormalizer_C.normalizeTag import kotlin.js.JsExport import kotlin.js.JsName import kotlin.js.JsStatic +import kotlin.jvm.JvmOverloads import kotlin.jvm.JvmStatic /** @@ -156,16 +157,21 @@ class TagList() : StringList(), ITagList { companion object TagList_C { /** - * Create a tag list from the given array; the tags are normalized. + * Create a tag list from the given array. Values being `null` or no [String] are ignored. * @param tags the tags. + * @param normalize if the values should be normalized. * @return the tag-list. + * @since 3.0 */ @JvmStatic @JsStatic - fun fromArray(tags: Array): TagList { - val list = TagList() - list.addAndNormalizeTags(*tags) - return list + @JvmOverloads + fun fromArray(tags: Array<*>, normalize: Boolean = true): TagList = TagList().apply { + setCapacity(tags.size) + for (tag in tags) { + if (tag is String) addTag(tag, normalize) + else if (tag is Char || tag is CharSequence) addTag(tag.toString(), normalize) + } } /** From b61aa3dbefbe03347aa05fdeaa210df8c7b3a697 Mon Sep 17 00:00:00 2001 From: Alexander Lowey-Weber Date: Mon, 31 Aug 2026 09:29:04 +0200 Subject: [PATCH 20/41] Embed helpers only used by Tuple into Tuple to be improved further in the future. Signed-off-by: Alexander Lowey-Weber --- .../naksha/model/FeatureMemberValues.kt | 224 ---------------- .../commonMain/kotlin/naksha/model/Tuple.kt | 249 +++++++++++++++++- 2 files changed, 238 insertions(+), 235 deletions(-) delete mode 100644 here-naksha-lib-model/src/commonMain/kotlin/naksha/model/FeatureMemberValues.kt diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/FeatureMemberValues.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/FeatureMemberValues.kt deleted file mode 100644 index 76988ffd6..000000000 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/FeatureMemberValues.kt +++ /dev/null @@ -1,224 +0,0 @@ -@file:Suppress("OPT_IN_USAGE") - -package naksha.model - -import naksha.base.AnyList -import naksha.base.AnyObject -import naksha.base.Int64 -import naksha.base.ListProxy -import naksha.base.MapProxy -import naksha.base.PlatformList -import naksha.base.Platform.PlatformCompanion.logger -import naksha.base.Platform.PlatformCompanion.toJSON -import naksha.base.TupleNumber -import naksha.geo.GeoUtil.GeoUtil_C.fromTWKB -import naksha.geo.SpGeometry -import naksha.model.objects.MemberType -import naksha.model.objects.NakshaFeature - -/** - * Helpers to walk a [NakshaFeature] by JSON path and coerce raw values to the expected [MemberType]. - * - * - [walkFeature]: descend a [NakshaFeature] using the member's path; returns _null_ if the path is missing. - * - [coerce]: coerce a raw value to the type of the member; returns _null_ and logs a warning on mismatch. - * - * @since 3.0 - */ -object FeatureMemberValues { - - /** - * Descend a [NakshaFeature] using the given [path] segments; returns _null_ if any segment is missing. - * - * @param feature the feature to walk. - * @param path the list of path segments (e.g. `["properties", "@ns:com:here:xyz", "updatedAt"]`). - * @return the value at the path, or _null_ if the path does not exist. - */ - fun walkFeature(feature: NakshaFeature, path: List): Any? { - var current: Any? = feature - for (segment in path) { - if (current == null) return null - current = when (current) { - is AnyObject -> current.getRaw(segment) - else -> return null - } - } - return current - } - - /** - * Coerce a raw value to the type expected by the member. - * - * For [MemberType.SPATIAL], the value is expected to be a [SpGeometry] (or [naksha.geo.SpPoint]) which will be - * encoded as TWKB bytes. For other types, the value is expected to already be the raw JSON value. - * - * @param value the raw value extracted from the feature. - * @param type the expected [MemberType]. - * @param featureId the feature identifier (for logging). - * @param memberName the member name (for logging). - * @return the coerced value, or _null_ if coercion failed. - */ - fun coerce(value: Any?, type: MemberType, featureId: String, memberName: String): Any? { - if (value == null) return null - return when (type) { - MemberType.BOOLEAN -> coerceBoolean(value, featureId, memberName) - MemberType.INT8 -> coerceInt8(value, featureId, memberName) - MemberType.INT16 -> coerceInt16(value, featureId, memberName) - MemberType.INT32 -> coerceInt32(value, featureId, memberName) - MemberType.INT64 -> coerceInt64(value, featureId, memberName) - MemberType.FLOAT32 -> coerceFloat32(value, featureId, memberName) - MemberType.FLOAT64 -> coerceFloat64(value, featureId, memberName) - MemberType.STRING -> coerceString(value, featureId, memberName) - MemberType.BYTE_ARRAY -> coerceByteArray(value, featureId, memberName) - MemberType.SPATIAL -> coerceSpatial(value, featureId, memberName) - MemberType.TAG_MAP -> coerceTags(value, featureId, memberName) - MemberType.TAG_MAP_FROM_ARRAY -> coerceTagsFromArray(value, featureId, memberName) - MemberType.TAG_LIST -> coerceTagListToJsonArray(value, featureId, memberName) - MemberType.TUPLE_NUMBER -> coerceTupleNumber(value, featureId, memberName) - else -> { - warnMismatch(featureId, memberName, type.toString(), value) - null - } - } - } - - // ------------------------------------------------------------------------- - // Individual coercion implementations - // ------------------------------------------------------------------------- - - private fun coerceBoolean(value: Any, featureId: String, memberName: String): Boolean? = when (value) { - is Boolean -> value - else -> { warnMismatch(featureId, memberName, "boolean", value); null } - } - - private fun coerceInt8(value: Any, featureId: String, memberName: String): Short? { - val asLong = numberToLongOrNull(value) ?: return null.also { warnMismatch(featureId, memberName, "int8", value) } - if (asLong !in Byte.MIN_VALUE.toLong()..Byte.MAX_VALUE.toLong()) { - warnMismatch(featureId, memberName, "int8 (out of range)", value) - return null - } - return asLong.toShort() - } - - private fun coerceInt16(value: Any, featureId: String, memberName: String): Short? { - val asLong = numberToLongOrNull(value) ?: return null.also { warnMismatch(featureId, memberName, "int16", value) } - if (asLong !in Short.MIN_VALUE.toLong()..Short.MAX_VALUE.toLong()) { - warnMismatch(featureId, memberName, "int16 (out of range)", value) - return null - } - return asLong.toShort() - } - - private fun coerceInt32(value: Any, featureId: String, memberName: String): Int? { - val asLong = numberToLongOrNull(value) ?: return null.also { warnMismatch(featureId, memberName, "int32", value) } - if (asLong !in Int.MIN_VALUE.toLong()..Int.MAX_VALUE.toLong()) { - warnMismatch(featureId, memberName, "int32 (out of range)", value) - return null - } - return asLong.toInt() - } - - private fun coerceInt64(value: Any, featureId: String, memberName: String): Int64? = when (value) { - is Int64 -> value - is Int -> Int64(value.toLong()) - is Long -> Int64(value) - is Short -> Int64(value.toLong()) - is Byte -> Int64(value.toLong()) - is Double -> if (value.isFinite() && value == value.toLong().toDouble()) Int64(value.toLong()) else { warnMismatch(featureId, memberName, "int64", value); null } - is Float -> if (value.isFinite() && value == value.toLong().toFloat()) Int64(value.toLong()) else { warnMismatch(featureId, memberName, "int64", value); null } - else -> { warnMismatch(featureId, memberName, "int64", value); null } - } - - private fun coerceFloat32(value: Any, featureId: String, memberName: String): Float? = when (value) { - is Float -> value - is Double -> value.toFloat() - is Int -> value.toFloat() - is Long -> value.toFloat() - is Int64 -> value.toLong().toFloat() - is Short -> value.toFloat() - is Byte -> value.toFloat() - else -> { warnMismatch(featureId, memberName, "float32", value); null } - } - - private fun coerceFloat64(value: Any, featureId: String, memberName: String): Double? = when (value) { - is Double -> value - is Float -> value.toDouble() - is Int -> value.toDouble() - is Long -> value.toDouble() - is Int64 -> value.toLong().toDouble() - is Short -> value.toDouble() - is Byte -> value.toDouble() - else -> { warnMismatch(featureId, memberName, "float64", value); null } - } - - private fun coerceString(value: Any, featureId: String, memberName: String): String? = when (value) { - is String -> value - else -> { warnMismatch(featureId, memberName, "string", value); null } - } - - private fun coerceByteArray(value: Any, featureId: String, memberName: String): ByteArray? = when (value) { - is ByteArray -> value - else -> { warnMismatch(featureId, memberName, "byte_array", value); null } - } - - /** - * Coerce a tuple-number value: an already-materialized [naksha.base.TupleNumber], or a string/byte-array encoding. - */ - private fun coerceTupleNumber(value: Any, featureId: String, memberName: String): TupleNumber? = when (value) { - is TupleNumber -> value - is String -> TupleNumber.fromStringOrGuid(value) - is ByteArray -> TupleNumber.fromByteArray(value) - else -> { warnMismatch(featureId, memberName, "tuple_number", value); null } - } - - /** - * Coerce a spatial value to a [SpGeometry]. - */ - private fun coerceSpatial(value: Any, featureId: String, memberName: String): SpGeometry? = when (value) { - is SpGeometry -> value - is ByteArray -> fromTWKB(value) - is MapProxy<*, *> -> value.proxy(SpGeometry::class) - else -> { warnMismatch(featureId, memberName, "spatial", value); null } - } - - private fun coerceTags(value: Any, featureId: String, memberName: String): TagMap? { - if (value !is AnyObject) { - warnMismatch(featureId, memberName, "tags", value) - return null - } - return value.proxy(TagMap::class) - } - - private fun coerceTagsFromArray(value: Any, featureId: String, memberName: String): TagMap? { - val tagList = when (value) { - is TagList -> value - is AnyList -> value.proxy(TagList::class) - is AnyObject -> value.proxy(TagList::class) - else -> { warnMismatch(featureId, memberName, "tags_from_array", value); return null } - } - return tagList.toTagMap() - } - - private fun coerceTagListToJsonArray(value: Any, featureId: String, memberName: String): String? { - val list: Any = when (value) { - is ListProxy<*> -> value - is PlatformList -> value.proxy(TagList::class) - else -> { warnMismatch(featureId, memberName, "tag_list", value); return null } - } - return try { toJSON(list) } catch (_: Exception) { warnMismatch(featureId, memberName, "tag_list", value); null } - } - - private fun numberToLongOrNull(value: Any): Long? = when (value) { - is Byte -> value.toLong() - is Short -> value.toLong() - is Int -> value.toLong() - is Long -> value - is Int64 -> value.toLong() - is Float -> if (value.isFinite() && value == value.toLong().toFloat()) value.toLong() else null - is Double -> if (value.isFinite() && value == value.toLong().toDouble()) value.toLong() else null - else -> null - } - - private fun warnMismatch(featureId: String, memberName: String, expected: String, value: Any) { - logger.warn("Member '$memberName' on feature '$featureId': expected $expected, got ${value::class.simpleName}") - } -} diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/Tuple.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/Tuple.kt index ceaf30b1e..4de1a199e 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/Tuple.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/Tuple.kt @@ -29,6 +29,7 @@ import naksha.base.NakshaError.NakshaErrorCompanion.ILLEGAL_STATE import naksha.base.NakshaException import naksha.base.Platform import naksha.base.Platform.PlatformCompanion.UNDEFINED +import naksha.base.Platform.PlatformCompanion.logger import naksha.base.PlatformListApi.PlatformListApiCompanion.array_get import naksha.base.PlatformListApi.PlatformListApiCompanion.array_set import naksha.base.PlatformMapApi.PlatformMapApiCompanion.map_set @@ -38,6 +39,8 @@ import naksha.base.Version import naksha.base.illegalArg import naksha.base.illegalState import naksha.base.internalError +import naksha.base.proxy +import naksha.geo.GeoUtil.GeoUtil_C.fromTWKB import naksha.model.objects.JsonPath import naksha.model.objects.MemberType import naksha.model.objects.NakshaCollection @@ -63,21 +66,21 @@ import kotlin.jvm.JvmStatic @JsExport data class Tuple @JvmOverloads constructor( /** - * Feature serialized with the encoding described by the collection's dataEncoding. + * The uncompressed `JBON` binary of the Feature, to be read with `JbonDecoder`. * @since 3.0 */ @JvmField val featureBytes: ByteArray, /** - * The members book provided by storage at read time. Contains dedicated member values, such as `id`, `tn`, etc. + * The _HEAP_ decoded members book provided by storage at read time. Contains the values of the [Member]. * @since 3.0 */ @JvmField val membersBook: IBook, /** - * After encoding a [NakshaFeature] into a [Tuple] using [encodeFeature] method, the [previousTupleNumber] will be set by the encoder to the [naksha.base.TupleNumber] of the given feature; if it had any. + * After encoding an object into a [Tuple] using [encodeFeature] method, the [previousTupleNumber] will be set in the generated [Tuple]. It will only be set by the encoder, if the given object contains a [TupleNumber][naksha.base.TupleNumber] of the state it had before being modified. In the XYZ specification this information was historically located in the jsonpath `properties->@ns:com:here:xyz->uuid`, but with modern `lib-base` support, the position can be freely selected. * - * This is metadata, it can as well be set manually, when a tuple is read from a storage. + * This is metadata, it can as well be set manually, when a tuple is read from a storage. It is not significant for the storage itself. * @since 3.0 */ @JvmField var previousTupleNumber: TupleNumber? = null @@ -232,8 +235,8 @@ data class Tuple @JvmOverloads constructor( TN -> newTn NEXT_VERSION -> null ORIGIN -> origin - GLOBAL_BOOK_FN -> globalBookTn?.featureNumber - CHANGE_COUNT -> (member.readInt64(f) ?: Int64(0)) + 1 + GLOBAL_BOOK_FN -> globalBookTn?.featureNumber?.toLong() + CHANGE_COUNT -> (member.readLong(f) ?: 0L) + 1L else -> member.read(f) } val procs = processors[memberName] @@ -242,13 +245,13 @@ data class Tuple @JvmOverloads constructor( memberValue = proc.processMember(session, collection, f, member, memberValue) } } - memberValue = FeatureMemberValues.coerce(memberValue, member.dataType, id, memberName) + memberValue = coerce(memberValue, member.dataType, id, memberName) membersBook.put(memberName, memberValue) } // Create the encoder with a custom member encoder. val encoder = JbEncoder2(globalBook) - encoder.withMemberEncoder { path: Array, pathEnd: Int, value: Any? -> + encoder.withMemberEncoder { path: Array, pathEnd: Int, _: Any? -> // Find the member whose declared path matches the current position and redirect its value into the members-book. members@ for (i in 0 until members.size) { val member = members[i] ?: continue @@ -281,9 +284,7 @@ data class Tuple @JvmOverloads constructor( } /** - * Copy-on-write view of [feature]: every container along the [naksha.model.objects.Member.path] - * is replaced by a shallow copy, everything else is shared with [feature]. - * Member writes into the result therefore never touch [feature]. + * Copy-on-write view of [NakshaFeature]: every container along the [naksha.model.objects.Member.path] is replaced by a shallow copy, everything else is shared with [NakshaFeature]. Member writes into the result therefore never touch [NakshaFeature]. */ fun copyOnWrite(original: NakshaFeature, path: JsonPath): NakshaFeature { val root = Platform.copy(original.platformObject(), false) as PlatformMap @@ -309,17 +310,243 @@ data class Tuple @JvmOverloads constructor( private fun isGzipped(bytes: ByteArray): Boolean = bytes.size >= 2 && bytes[0] == 0x1F.toByte() && bytes[1] == 0x8B.toByte() + @Suppress("unused") private fun isJbon2(bytes: ByteArray): Boolean = bytes.size >= 4 && bytes[0] == JB2_MAGIC[0] && bytes[1] == JB2_MAGIC[1] && bytes[2] == JB2_MAGIC[2] && bytes[3] == JB2_MAGIC[3] + @Suppress("unused") private fun isJson(bytes: ByteArray): Boolean { val b = bytes[0] return b == 0x7B.toByte() || b == 0x5B.toByte() || b == 0x20.toByte() || b == 0x09.toByte() || b == 0x0A.toByte() || b == 0x0D.toByte() } + + + /** + * Descend a [NakshaFeature] using the given [path] segments; returns _null_ if any segment is missing. + * + * @param feature the feature to walk. + * @param path the list of path segments (e.g. `["properties", "@ns:com:here:xyz", "updatedAt"]`). + * @return the value at the path, or _null_ if the path does not exist. + */ + private fun walkFeature(feature: NakshaFeature, path: List): Any? { + var current: Any? = feature + for (segment in path) { + if (current == null) return null + current = when (current) { + is AnyObject -> current.getRaw(segment) + else -> return null + } + } + return current + } + + /** + * Coerce a raw value to the type expected by the member. + * + * For [MemberType.SPATIAL], the value is expected to be a [SpGeometry] (or [naksha.geo.SpPoint]) which will be + * encoded as TWKB bytes. For other types, the value is expected to already be the raw JSON value. + * + * @param value the raw value extracted from the feature. + * @param type the expected [MemberType]. + * @param featureId the feature identifier (for logging). + * @param memberName the member name (for logging). + * @return the coerced value, or _null_ if coercion failed. + */ + private fun coerce(value: Any?, type: MemberType, featureId: String, memberName: String): Any? { + if (value == null) return null + return when (type) { + MemberType.BOOLEAN -> coerceBoolean(value, featureId, memberName) + MemberType.INT8 -> coerceInt8(value, featureId, memberName) + MemberType.INT16 -> coerceInt16(value, featureId, memberName) + MemberType.INT32 -> coerceInt32(value, featureId, memberName) + MemberType.INT64 -> coerceInt64(value, featureId, memberName) + MemberType.FLOAT32 -> coerceFloat32(value, featureId, memberName) + MemberType.FLOAT64 -> coerceFloat64(value, featureId, memberName) + MemberType.STRING -> coerceString(value, featureId, memberName) + MemberType.BYTE_ARRAY -> coerceByteArray(value, featureId, memberName) + MemberType.SPATIAL -> coerceSpatial(value, featureId, memberName) + MemberType.TAG_MAP -> coerceTagMap(value, featureId, memberName) + MemberType.TAG_LIST -> coerceTagList(value, featureId, memberName) + MemberType.TUPLE_NUMBER -> coerceTupleNumber(value, featureId, memberName) + else -> { + warnMismatch(featureId, memberName, type.toString(), value) + null + } + } + } + + // ------------------------------------------------------------------------- + // Individual coercion implementations + // ------------------------------------------------------------------------- + + private fun coerceBoolean(value: Any, featureId: String, memberName: String): Boolean? = when (value) { + is Boolean -> value + else -> { warnMismatch(featureId, memberName, "Boolean", value); null } + } + + private fun coerceInt8(value: Any, featureId: String, memberName: String): Byte? { + val asLong = numberToLongOrNull(value) ?: return null.also { warnMismatch(featureId, memberName, "Byte", value) } + if (asLong !in Byte.MIN_VALUE.toLong()..Byte.MAX_VALUE.toLong()) { + warnMismatch(featureId, memberName, "Byte", value) + return null + } + return asLong.toByte() + } + + private fun coerceInt16(value: Any, featureId: String, memberName: String): Short? { + val asLong = numberToLongOrNull(value) ?: return null.also { warnMismatch(featureId, memberName, "Short", value) } + if (asLong !in Short.MIN_VALUE.toLong()..Short.MAX_VALUE.toLong()) { + warnMismatch(featureId, memberName, "Short", value) + return null + } + return asLong.toShort() + } + + private fun coerceInt32(value: Any, featureId: String, memberName: String): Int? { + val asLong = numberToLongOrNull(value) ?: return null.also { warnMismatch(featureId, memberName, "Int", value) } + if (asLong !in Int.MIN_VALUE.toLong()..Int.MAX_VALUE.toLong()) { + warnMismatch(featureId, memberName, "Int", value) + return null + } + return asLong.toInt() + } + + // TODO: Needs to become Long! + private fun coerceInt64(value: Any, featureId: String, memberName: String): Long? = when (value) { + is Int64 -> value.toLong() + is Int -> value.toLong() + is Long -> value + is Short -> value.toLong() + is Byte -> value.toLong() + is Double -> if (value.isFinite() && value == value.toLong().toDouble()) value.toLong() + else { warnMismatch(featureId, memberName, "Long", value); null } + is Float -> if (value.isFinite() && value == value.toLong().toFloat()) value.toLong() + else { warnMismatch(featureId, memberName, "Long", value); null } + else -> { warnMismatch(featureId, memberName, "Long", value); null } + } + + private fun float32OrNull(value: Any?): Float? = when (value) { + is Float -> value + is Double -> value.toFloat() + is Int -> value.toFloat() + is Long -> value.toFloat() + is Int64 -> value.toLong().toFloat() + is Short -> value.toFloat() + is Byte -> value.toFloat() + else -> null + } + + private fun coerceFloat32(value: Any, featureId: String, memberName: String): Float? { + val v = float32OrNull(value) + if (v == null) warnMismatch(featureId, memberName, "Float", value) + return v + } + + private fun float64OrNull(value: Any?): Double? = when (value) { + is Double -> value + is Float -> value.toDouble() + is Int -> value.toDouble() + is Long -> value.toDouble() + is Int64 -> value.toLong().toDouble() + is Short -> value.toDouble() + is Byte -> value.toDouble() + else -> null + } + + private fun coerceFloat64(value: Any, featureId: String, memberName: String): Double? { + val v = float64OrNull(value) + if (v == null) warnMismatch(featureId, memberName, "Double", value) + return v + } + + private fun coerceString(value: Any, featureId: String, memberName: String): String? = when (value) { + is String -> value + is Char, is CharSequence -> value.toString() + else -> { warnMismatch(featureId, memberName, "String", value); null } + } + + private fun coerceByteArray(value: Any, featureId: String, memberName: String): ByteArray? = when (value) { + is ByteArray -> value + else -> { warnMismatch(featureId, memberName, "ByteArray", value); null } + } + + private fun tupleNumberOrNull(value: Any?): TupleNumber? = when (value) { + is TupleNumber -> value + is String -> TupleNumber.fromStringOrGuid(value) + is ByteArray -> TupleNumber.fromByteArray(value) + else -> null + } + + /** + * Coerce a tuple-number value: an already-materialized [naksha.base.TupleNumber], or a string/byte-array encoding. + */ + private fun coerceTupleNumber(value: Any, featureId: String, memberName: String): TupleNumber? { + val v = tupleNumberOrNull(value) + if (v == null) warnMismatch(featureId, memberName, "TupleNumber", value) + return v + } + + /** + * Coerce a spatial value to a [SpGeometry]. + */ + private fun coerceSpatial(value: Any, featureId: String, memberName: String): SpGeometry? { + val geometry = when (value) { + is SpGeometry -> value + is ByteArray -> fromTWKB(value) + else -> value.proxy(SpGeometry::class) + } + return geometry + ?: { warnMismatch(featureId, memberName, "SpGeometry", value); null } as SpGeometry? + } + + private fun coerceTagMap(value: Any, featureId: String, memberName: String): TagMap? { + val tagMap = value.proxy(TagMap::class) + if (tagMap != null) return tagMap + warnMismatch(featureId, memberName, "TagMap", value) + return null + // TODO: Nice Compiler Bug, this code should replace the above, but compiler complains! + // The exact same code works above in `coerceSpatial` ? + // return tagMap ?: { warnMismatch(featureId, memberName, "TagMap", value); null } as TagMap? + } + + private fun coerceTagList(value: Any, featureId: String, memberName: String): TagList? { + val list = when (value) { + is TagList -> value + is Array<*> -> TagList().apply { + setCapacity(value.size) + for (v in value) if (v is String) addTag(v, true) + } + else -> value.proxy(TagList::class) + } + if (list != null) return list + warnMismatch(featureId, memberName, "tag_list", value) + return null + } + + /** + * Convert the given number into [Long] or return `null`. + * @param value the potential value. + * @return either [Long] or `null`. + * @since 3.0 + */ + private fun numberToLongOrNull(value: Any?): Long? = when (value) { + is Byte -> value.toLong() + is Short -> value.toLong() + is Int -> value.toLong() + is Long -> value + is Int64 -> value.toLong() + is Float -> if (value.isFinite() && value == value.toLong().toFloat()) value.toLong() else null + is Double -> if (value.isFinite() && value == value.toLong().toDouble()) value.toLong() else null + else -> null + } + + private fun warnMismatch(featureId: String, memberName: String, expected: String, value: Any) { + logger.warn("Member '$memberName' on feature '$featureId': expected $expected, got ${value::class.simpleName}") + } } override fun equals(other: Any?): Boolean { From df1139567f258d2e1c2871fdc8cb594e4c563536 Mon Sep 17 00:00:00 2001 From: Alexander Lowey-Weber Date: Mon, 31 Aug 2026 09:39:43 +0200 Subject: [PATCH 21/41] Remove TAG_MAP_FROM_ARRAY Signed-off-by: Alexander Lowey-Weber --- .../kotlin/naksha/model/objects/MemberType.kt | 238 ++++++++++++------ .../naksha/model/objects/TagMapMember.kt | 3 +- .../naksha/model/request/query/TagExists.kt | 7 +- .../naksha/model/request/query/TagQuery.kt | 6 +- .../model/request/query/TagSetContains.kt | 4 +- .../kotlin/naksha/psql/PgCollection.kt | 8 +- .../commonMain/kotlin/naksha/psql/PgIndex.kt | 5 +- .../commonMain/kotlin/naksha/psql/PgType.kt | 18 +- 8 files changed, 170 insertions(+), 119 deletions(-) diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/MemberType.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/MemberType.kt index 64fed33e3..fd63b78b0 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/MemberType.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/MemberType.kt @@ -7,33 +7,29 @@ import naksha.base.JsEnum import naksha.geo.SpGeometry import naksha.base.NakshaError.NakshaErrorCompanion.INITIALIZATION_FAILED import naksha.base.NakshaException +import naksha.base.Platform.PlatformCompanion.fromJSON import naksha.model.TagMap import naksha.base.TupleNumber +import naksha.base.proxy +import naksha.geo.GeoUtil +import naksha.model.TagList +import naksha.model.TagNormalizer.TagNormalizer_C.normalizeTag import kotlin.js.JsExport import kotlin.jvm.JvmField +import kotlin.jvm.JvmOverloads import kotlin.reflect.KClass /** - * The logical data type of a [Member]. + * The type of [Member]. The type defines what the storage expects as value in the member book of the [Tuple][naksha.model.Tuple], either as _HEAP_ object or as binary. * - * - Primitives: [BOOLEAN], [INT8], [INT16], [INT32], [INT64], [FLOAT32], [FLOAT64], [STRING], [BYTE_ARRAY]. - * - [SPATIAL]: a geometry stored as raw TWKB bytes. The storage persists this as a binary column and - * supports spatial queries. Only a [IndexType.SPATIAL] index may be placed on a [SPATIAL] member. - * - [TAG_MAP]: a map whose keys are strings and values are primitives (matches JBON2 tag-map specification). - * The storage persists this as a flat key/value map that supports containment queries. - * - [TAG_MAP_FROM_ARRAY]: like [TAG_MAP] but the input is a `TagList` (Naksha tag-array syntax, e.g. - * `["key=value", "name:=42"]`). The list is converted to a tag-map at write time and stored in the - * same flat key/value representation as [TAG_MAP]. Beware that the conversion has a side effect: - * reading the feature back returns the tags re-flattened from the map, so the original array - * order is **not** preserved. - * Only valid as a [Member] type; not a valid [IndexType]. - * To index a [TAG_MAP_FROM_ARRAY] column use [IndexType.TAG_MAP]. - * - [TAG_LIST]: a list of unique primitive values (booleans, numbers, strings). Value order is - * significant, but must not have duplicates, null or undefined. The storage persists the list - * unmodified, so the element order is guaranteed to be preserved when reading the feature back. - * Supports element-containment queries via [IndexType.TAG_LIST]. This is the default type of the - * standard `tags` member, which keeps 100% downward compatibility with the classic XYZ tags array - * at `properties -> @ns:com:here:xyz -> tags`. + * The member book is generated by the [encoder][naksha.model.Tuple.encodeFeature], which must produce the values in the defined [MemberType] from the given input feature _(for example [NakshaFeature])_. + * + * The [decoder][naksha.model.Tuple.decodeFeature] reverses this. It receives a [Tuple][naksha.model.Tuple] from the storage which contains the [Member] values in the defined [MemberType] and integrates them back into the output feature _(for example [NakshaFeature])_. + * + * - [BOOLEAN], [INT8], [INT16], [INT32], [INT64], [FLOAT32], [FLOAT64], [STRING], [BYTE_ARRAY] —> Primitives. + * - [SPATIAL] —> A geometry represented in memory as [SpGeometry] and binary as [TWKB](https://github.com/TWKB/Specification/blob/master/twkb.md). + * - [TAG_LIST] —> A list of strings _([TagList])_. The order is significant and guaranteed. The storage persists the list unmodified, so the element order is guaranteed to be preserved when reading back from the storage. + * - [TAG_MAP] —> A map with keys being strings and values being primitives _([TagMap])_. The order of the key-value pairs is not guaranteed by the storage, when converted into a [Member]. * @since 3.0 */ @JsExport @@ -45,133 +41,167 @@ class MemberType : JsEnum() { override fun initClass() {} companion object MemberType_C { - /** - * Boolean. - * @since 3.0 - */ - @JvmField - val BOOLEAN = defIgnoreCase(MemberType::class, "boolean") { self -> self.sortOrder = 6; self.subtype = BoolMember::class } + // TODO: We need to update the documentation of the members, so that they match the up-to-date one provided for the class! /** - * 8-bit signed integer in storage, but when reading from book, decode as long. + * [Boolean] — Boolean. * @since 3.0 */ @JvmField - val INT8 = defIgnoreCase(MemberType::class, "int8") { self -> self.sortOrder = 5; self.subtype = Int8Member::class } + val BOOLEAN = defIgnoreCase(MemberType::class, "boolean") { + self -> self.sortOrder = 6 + self.subtype = BoolMember::class + self.valuesType = Boolean::class + } /** - * 16-bit signed integer in storage, but when reading from book, decode as long. + * [Byte] — 8-bit signed integer in storage, but when reading from book. * @since 3.0 */ @JvmField - val INT16 = defIgnoreCase(MemberType::class, "int16") { self -> self.sortOrder = 4; self.subtype = Int16Member::class } + val INT8 = defIgnoreCase(MemberType::class, "int8") { + self -> self.sortOrder = 5 + self.subtype = Int16Member::class + self.valuesType = Int::class + } /** - * 32-bit signed integer in storage, but when reading from book, decode as long. + * [Short] — 16-bit signed integer in storage, but when reading from book. * @since 3.0 */ @JvmField - val INT32 = defIgnoreCase(MemberType::class, "int32") { self -> self.sortOrder = 2; self.subtype = Int32Member::class } + val INT16 = defIgnoreCase(MemberType::class, "int16") { + self -> self.sortOrder = 4 + self.subtype = Int16Member::class + self.valuesType = Int::class + } /** - * 64-bit signed integer. + * [Int] — 32-bit signed integer in storage, but when reading from book. * @since 3.0 */ @JvmField - val INT64 = defIgnoreCase(MemberType::class, "int64") { self -> self.sortOrder = 0; self.subtype = Int64Member::class } + val INT32 = defIgnoreCase(MemberType::class, "int32") { + self -> self.sortOrder = 2 + self.subtype = Int32Member::class + self.valuesType = Int::class + } /** - * 32-bit IEEE-754 floating point in storage, but when reading from book, decode as double. + * [Long] — 64-bit signed integer. * @since 3.0 */ @JvmField - val FLOAT32 = defIgnoreCase(MemberType::class, "float32"){ self -> self.sortOrder = 3; self.subtype = Float32Member::class } + val INT64 = defIgnoreCase(MemberType::class, "int64") { + self -> self.sortOrder = 0 + self.subtype = Int64Member::class + self.valuesType = Long::class + } /** - * 64-bit IEEE-754 floating point. + * [Float] — 32-bit IEEE-754 floating point in storage, but when reading from book. * @since 3.0 */ @JvmField - val FLOAT64 = defIgnoreCase(MemberType::class, "float64") { self -> self.sortOrder = 1; self.subtype = Float64Member::class } + val FLOAT32 = defIgnoreCase(MemberType::class, "float32") { + self -> self.sortOrder = 3 + self.subtype = Float32Member::class + self.valuesType = Float::class + } /** - * Variable-length string. + * [Double] — 64-bit IEEE-754 floating point. * @since 3.0 */ @JvmField - val STRING = defIgnoreCase(MemberType::class, "string") { self -> self.sortOrder = 7; self.subtype = StringMember::class } + val FLOAT64 = defIgnoreCase(MemberType::class, "float64") { + self -> self.sortOrder = 1 + self.subtype = Float64Member::class + self.valuesType = Double::class + } /** - * Raw byte array. + * [String] — Variable-length string. * @since 3.0 */ @JvmField - val BYTE_ARRAY = defIgnoreCase(MemberType::class, "byte_array") { self -> self.sortOrder = 13; self.subtype = ByteArrayMember::class } + val STRING = defIgnoreCase(MemberType::class, "string") { + self -> self.sortOrder = 7 + self.subtype = StringMember::class + self.valuesType = String::class + } /** - * A tuple-number, can be encoded as string or byte-array _(storage decides)_. To be used with [IndexType.BTREE]. + * [ByteArray] — Raw bytes. * @since 3.0 */ @JvmField - val TUPLE_NUMBER = defIgnoreCase(MemberType::class, "tuple_number") { self -> self.sortOrder = 12; self.subtype = TupleNumberMember::class } + val BYTE_ARRAY = defIgnoreCase(MemberType::class, "byte_array") { + self -> self.sortOrder = 12 + self.subtype = ByteArrayMember::class + self.valuesType = ByteArray::class + } /** - * A geometry stored as raw [TWKB](https://github.com/nicowillis/twkb) bytes. - * - * The storage layer (`lib-psql`) persists this as a `bytea` column with `STORAGE EXTERNAL` - * and interprets it as TWKB-encoded geometry for spatial indexing and queries. - * - * Only [IndexType.SPATIAL] may be used with a `SPATIAL` member. + * [TupleNumber] — A tuple-number, represented as [TupleNumber]. * @since 3.0 */ @JvmField - val SPATIAL = defIgnoreCase(MemberType::class, "spatial") { self -> self.sortOrder = 11; self.subtype = SpatialMember::class } + val TUPLE_NUMBER = defIgnoreCase(MemberType::class, "tuple_number") { + self -> self.sortOrder = 11 + self.subtype = TupleNumberMember::class + self.valuesType = TupleNumber::class + } /** - * A map whose keys are strings and values are primitives, following the JBON2 tag-map - * specification. The storage persists this as a flat key/value map that supports - * containment queries. - * - * Indexed via [IndexType.TAG_MAP]. + * [SpGeometry] — A GeoJSON geometry, the binary representation are [TWKB](https://github.com/nicowillis/twkb) bytes. * @since 3.0 */ @JvmField - val TAG_MAP = defIgnoreCase(MemberType::class, "tag_map") { self -> self.sortOrder = 8; self.subtype = TagMapMember::class } + val SPATIAL = defIgnoreCase(MemberType::class, "spatial") { + self -> self.sortOrder = 10 + self.subtype = SpatialMember::class + self.valuesType = SpGeometry::class + } + /** - * A string-array using Naksha tag syntax that is expanded into a [TAG_MAP] map at write time. - * Provided for downward compatibility with XYZ Hub and previous Naksha v2 clients that send - * tags as arrays rather than maps. The order of the array is **not** preserved when reading the feature back, - * because the values are split into key/value pairs and stored in a map. + * [TagList] — A list of strings. * - * Input is `["key=value", "name:=42"]`; materialized form is `{"key":"value","name":42}`. - * Stored in the same flat key/value representation as [TAG_MAP]. - * - * **Not valid as an [IndexType].** To index this column use [IndexType.TAG_MAP]. + * This is the default type of the standard `tags` member in the classic XYZ format, which encodes the `tags` in the `JSON` object at `properties->@ns:com:here:xyz->tags`, example: + * ```json + * { + * "properties": { + * "@ns:com:here:xyz": { + * "tags": ["foo", "bar"] + * } + * } + * } + * ``` * @since 3.0 */ @JvmField - val TAG_MAP_FROM_ARRAY = defIgnoreCase(MemberType::class, "tag_map_from_array") { self -> self.sortOrder = 9; self.subtype = TagMapMember::class } + val TAG_LIST = defIgnoreCase(MemberType::class, "tag_list") { + self -> self.sortOrder = 9 + self.subtype = TagListMember::class + self.valuesType = TagList::class + } /** - * A list of unique primitive values (booleans, numbers, strings), following the JBON2 - * TagList specification: entries must not be `null` or duplicates, and the order is - * significant. The storage persists the list unmodified (as a JSON array in `jsonb`), so - * the element order is guaranteed to be preserved when reading the feature back. - * - * This is the default type of the standard `tags` member (the classic XYZ tags array at - * `properties -> @ns:com:here:xyz -> tags`, e.g. `["foo", "bar"]`). In contrast to - * [TAG_MAP_FROM_ARRAY] the values are not split into key/value pairs, therefore only full - * elements can be searched, not keys or values. - * - * Indexed via [IndexType.TAG_LIST]. + * [TagMap] — A map whose keys are strings and values are primitives. * @since 3.0 */ @JvmField - val TAG_LIST = defIgnoreCase(MemberType::class, "tag_list") { self -> self.sortOrder = 10; self.subtype = TagListMember::class } + val TAG_MAP = defIgnoreCase(MemberType::class, "tag_map") { + self -> self.sortOrder = 8 + self.subtype = TagMapMember::class + self.valuesType = TagMap::class + } - init { + init { // Validate sort orders form a contiguous range [0, N); done here, after all types have loaded. + // Note: This order is used to sort members in storages. + // We first want all fixed size items with 8 byte, then 4 bytes, 2 byte, 1 byte, then flexible types. val orders = ArrayList() val i = iterate(MemberType::class) while (i.hasNext()) orders.add(i.next().sortOrder) @@ -186,7 +216,18 @@ class MemberType : JsEnum() { } /** - * The concrete subtype of this class. + * The Kotlin type that generally represents this member type. + * + * Beware the for primitives technically smaller values are as well accepted, therefore use [isInstance] to test if a value is valid for a certain member type and not the `isInstance` method of this class! + * + * The intent for this property is debugging purpose, for example `"exepcted ${memberType.valueType.simpleName}"`, which may print something like `"expected Long"` or `"expected TagMap"`. + * @since 3.0 + */ + var valuesType: KClass<*> = Any::class + private set + + /** + * The subtype of this class, so the specialized member type, for example [StringMember]. * @since 3.0 */ var subtype: KClass = Member::class @@ -194,6 +235,8 @@ class MemberType : JsEnum() { /** * Tests if the given value is of this type. + * + * **Note**: For [TAG_MAP_FROM_TAG_LIST] the expectation is [TagList], **not** [TagMap]! * @param value the value to test. * @return `true` if the value is of this type; false otherwise. */ @@ -211,11 +254,46 @@ class MemberType : JsEnum() { TUPLE_NUMBER -> value is TupleNumber SPATIAL -> value is SpGeometry TAG_MAP -> value is TagMap - TAG_MAP_FROM_ARRAY, TAG_LIST -> value is List<*> + TAG_LIST -> value is TagList else -> false } } + /** + * Converts the given value into the expected format of the type or returns `null`. For example for [INT8] numbers will be cast into [Byte]. + * @param value the value to convert. + * @param normalize only for [TAG_LIST], if the value should be normalized or are from a trusted source. + * @return the converted value or `null`. + * @since 3.0 + */ + @JvmOverloads + fun convert(value: Any?, normalize: Boolean = true): Any? = when (this) { + INT8 -> if (value is Number) value.toByte() else if (value is Int64) value.toByte() else null + INT16 -> if (value is Number) value.toShort() else if (value is Int64) value.toShort() else null + INT32 -> if (value is Number) value.toInt() else if (value is Int64) value.toInt() else null + INT64 -> if (value is Number) value.toLong() else if (value is Int64) value.toLong() else null + FLOAT32 -> if (value is Number) value.toFloat() else if (value is Int64) value.toFloat() else null + FLOAT64 -> if (value is Number) value.toDouble() else if (value is Int64) value.toDouble() else null + STRING -> value as? String ?: if (value is Char || value is CharSequence) value.toString() else null + BYTE_ARRAY -> value as? ByteArray + TUPLE_NUMBER -> value as? TupleNumber ?: + if (value is String) TupleNumber.fromString(value) + else if (value is ByteArray) TupleNumber.fromByteArray(value) + else null + SPATIAL -> value as? SpGeometry ?: + if (value is String) fromJSON(value).proxy(SpGeometry::class) + else if (value is ByteArray) GeoUtil.fromTWKB(value) + else value.proxy(SpGeometry::class) + TAG_LIST -> value as? TagList ?: + if (value is Array<*>) TagList.fromArray(value) + else if (value is String) fromJSON(value).proxy(TagList::class) + else value.proxy(TagList::class) + TAG_MAP -> value as? TagMap ?: + if (value is String) fromJSON(value).proxy(TagMap::class) + else value.proxy(TagMap::class) + else -> null + } + /** * The sort order of the type to ensure no padding is needed, so `INT8`, `FLOAT8`, `INT4`, `FLOAT4`, ... * @since 3.0 diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/TagMapMember.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/TagMapMember.kt index db06d5334..ec8066b75 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/TagMapMember.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/TagMapMember.kt @@ -5,7 +5,6 @@ import naksha.model.Tuple import naksha.base.illegalArg import naksha.base.illegalState import naksha.model.objects.MemberType.MemberType_C.TAG_MAP -import naksha.model.objects.MemberType.MemberType_C.TAG_MAP_FROM_ARRAY import kotlin.js.JsName class TagMapMember() : TypedMember() { @@ -28,7 +27,7 @@ class TagMapMember() : TypedMember() { /** Creates a tag map member from an existing [Member], validating its type. */ @JsName("from") constructor(member: Member, path: JsonPath? = null) : this() { - if ((member.dataType != TAG_MAP) && (member.dataType != TAG_MAP_FROM_ARRAY)) throw illegalArg("The given member is not of tags type") + if (member.dataType != TAG_MAP) throw illegalArg("The given member is not of tags type") this.name = member.name this.dataType = TAG_MAP this.path = path?.validate() ?: member.path diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/query/TagExists.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/query/TagExists.kt index 35332c441..8a45ea1fd 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/query/TagExists.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/query/TagExists.kt @@ -6,12 +6,7 @@ import kotlin.js.JsExport import kotlin.js.JsName /** - * Tests if the tag with given name exists, ignoring the value. - * - * For map-form tags ([naksha.model.objects.MemberType.TAG_MAP] / [naksha.model.objects.MemberType.TAG_MAP_FROM_ARRAY]) - * this tests if the key exists. For tag-list-form tags ([naksha.model.objects.MemberType.TAG_LIST], the default) - * this tests if the full string element exists, e.g. `TagExists("foo")` matches a feature tagged - * `["foo", "bar"]`. + * Tests if the tag _(key)_ with given name exists in a [TagMap][naksha.model.TagMap] or [TagList][naksha.model.TagList], ignoring the value. For example `TagExists("foo")` matches a feature tagged `["foo", "bar"]` or `{"foo":5, "bar":"demo"}`. * @since 3.0.0 */ @JsExport diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/query/TagQuery.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/query/TagQuery.kt index 21030eb5a..47242be7b 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/query/TagQuery.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/query/TagQuery.kt @@ -9,11 +9,7 @@ import kotlin.js.JsExport /** * A general form of a tag query without any operation. * - * Note: the `TagValueIs*` and [TagValueMatches] queries operate on keys/values and therefore only - * match map-form tags ([naksha.model.objects.MemberType.TAG_MAP] / - * [naksha.model.objects.MemberType.TAG_MAP_FROM_ARRAY]). Against the default set-form tags - * ([naksha.model.objects.MemberType.TAG_LIST]) the values are never split into key/value pairs; use - * [TagExists] or [TagSetContains] to match full elements instead. + * Note: the `TagValueIs*` and [TagValueMatches] queries operate on keys/values and therefore only match [TagMap][naksha.model.TagMap]. * @since 3.0.0 * @see TagExists * @see TagSetContains diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/query/TagSetContains.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/query/TagSetContains.kt index 53c55d302..e0635edb2 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/query/TagSetContains.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/query/TagSetContains.kt @@ -19,9 +19,7 @@ import kotlin.js.JsName * complete elements can be matched: a feature tagged `["foo=bar"]` is found by * `TagSetContains("foo=bar")`, not by `TagSetContains("foo")`. * - * This query does **not** match map-form tags ([naksha.model.objects.MemberType.TAG_MAP] or - * [naksha.model.objects.MemberType.TAG_MAP_FROM_ARRAY]); use [TagExists] and the `TagValueIs*` queries - * for those. + * This query does **not** match [TagMap][naksha.model.TagMap]. * @since 3.0 */ @JsExport diff --git a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgCollection.kt b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgCollection.kt index ba1c0d02c..55d771db9 100644 --- a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgCollection.kt +++ b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgCollection.kt @@ -16,7 +16,6 @@ import naksha.model.objects.MemberType.MemberType_C.SPATIAL import naksha.model.objects.MemberType.MemberType_C.STRING import naksha.model.objects.MemberType.MemberType_C.TAG_LIST import naksha.model.objects.MemberType.MemberType_C.TAG_MAP -import naksha.model.objects.MemberType.MemberType_C.TAG_MAP_FROM_ARRAY import naksha.model.objects.MemberType.MemberType_C.TUPLE_NUMBER import naksha.model.objects.NakshaCollection import naksha.model.objects.XyzIndices @@ -115,10 +114,11 @@ open class PgCollection internal constructor( } return when (memberType) { - //TUPLE_NUMBER is already handled differently (split into PgColumn.FnColumn and PgColumn.VersionColumn), where this method is called - BYTE_ARRAY -> PgColumn(index, memberName, memberType, "STORAGE $EXTENDED") + // The standard tuple-number (tn) is handled differently, split into feature-number and version + // Other tuple-numbers are currently not supported, but they will be, we will store them as byte-array + BYTE_ARRAY, TUPLE_NUMBER -> PgColumn(index, memberName, memberType, "STORAGE $EXTENDED") STRING -> PgColumn(index, memberName, STRING, "STORAGE $MAIN COLLATE \"C\"") - TAG_MAP, TAG_MAP_FROM_ARRAY, TAG_LIST -> PgColumn(index, memberName, memberType, "STORAGE $MAIN") + TAG_MAP, TAG_LIST -> PgColumn(index, memberName, memberType, "STORAGE $MAIN") SPATIAL -> PgColumn(index, memberName, memberType, "STORAGE $EXTERNAL") else -> PgColumn(index, memberName, memberType, "STORAGE $PLAIN") } diff --git a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgIndex.kt b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgIndex.kt index 0a48b12b2..badde70d3 100644 --- a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgIndex.kt +++ b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgIndex.kt @@ -2,6 +2,7 @@ package naksha.psql import naksha.base.illegalArg import naksha.model.objects.Index +import naksha.model.objects.Member import naksha.model.objects.MemberType import naksha.psql.PgUtil.PgUtilCompanion.quoteIdent import kotlin.js.JsExport @@ -67,9 +68,9 @@ data class PgIndex( MemberType.STRING -> Pair("btree", "${column.ident} COLLATE \"C\" text_pattern_ops") // A two-dimensional gist index over the TWKB geometry, via the naksha_2d() helper. MemberType.SPATIAL -> Pair("gist", "naksha_2d(${column.ident})") - MemberType.TAG_MAP, - MemberType.TAG_MAP_FROM_ARRAY -> Pair("gin", "${column.ident} jsonb_ops") + MemberType.TAG_MAP -> Pair("gin", "${column.ident} jsonb_ops") MemberType.TAG_LIST -> Pair("gin", "${column.ident} array_ops") + // tuple-number and boolean so far else -> throw illegalArg("The member type ${column.memberType} of column '$column' of index '$indexName' is not a valid index target") } } diff --git a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgType.kt b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgType.kt index 482779634..652a1bd73 100644 --- a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgType.kt +++ b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgType.kt @@ -182,7 +182,7 @@ class PgType : JsEnum() { /** * JSONB column type, bound as text (JSON). * - * Used by storages to materialize [naksha.model.objects.MemberType.TAG_MAP], [naksha.model.objects.MemberType.TAG_MAP_FROM_ARRAY] (JSON object), and [naksha.model.objects.MemberType.TAG_LIST] (JSON array) members. + * Used by storages to materialize [TagMap][naksha.model.TagMap]. * @since 3.0 */ @JvmField @@ -191,18 +191,6 @@ class PgType : JsEnum() { it.klass = String::class } - /** - * `jsonb[]` array type. Element values are JSON text strings (the on-wire form Postgres accepts for `jsonb`). - * - * @since 3.0 - */ - @JvmField - @JsStatic - val JSONB_ARRAY = defIgnoreCase(PgType::class, "jsonb[]") { - it.componentType = JSONB - it.klass = Array::class - } - /** * Returns the [PgType] from the given string. * @param name the name, for example `"int"`. @@ -283,7 +271,6 @@ class PgType : JsEnum() { MemberType.FLOAT64 -> DOUBLE MemberType.STRING -> STRING MemberType.TAG_MAP -> JSONB - MemberType.TAG_MAP_FROM_ARRAY -> JSONB MemberType.TAG_LIST -> STRING_ARRAY // MemberType.BYTE_ARRAY -> BYTE_ARRAY // MemberType.TUPLE_NUMBER -> BYTE_ARRAY @@ -367,9 +354,6 @@ class PgType : JsEnum() { // We do not support Array, it's hard to detect cross-platform! BYTE_ARRAY_ARRAY -> value.proxy(AnyList::class)?.toByteArrayArray(true) ?: throw illegalArg("The given value is not an list: $value") - // We do not support Array, it's hard to detect cross-platform! - JSONB_ARRAY -> value.proxy(AnyList::class)?.toJsonArray() - ?: throw illegalArg("The given value is not an list: $value") else -> throw internalError("Missing when-case for this Postgres Type: $this") } } From 5ff11706c7c3ed540ab6d987394af3b5f148c50d Mon Sep 17 00:00:00 2001 From: Alexander Lowey-Weber Date: Mon, 31 Aug 2026 09:40:03 +0200 Subject: [PATCH 22/41] First part of replacing Int64 with Long Signed-off-by: Alexander Lowey-Weber --- .../commonMain/kotlin/naksha/base/Proxy.kt | 2 +- .../kotlin/naksha/model/objects/Index.kt | 2 +- .../naksha/model/objects/Int16Member.kt | 4 +- .../naksha/model/objects/Int32Member.kt | 4 +- .../naksha/model/objects/Int64Member.kt | 7 +- .../kotlin/naksha/model/objects/Int8Member.kt | 4 +- .../kotlin/naksha/model/objects/Member.kt | 18 +- .../naksha/model/objects/XyzProcessors.kt | 11 +- .../kotlin/naksha/psql/PgColumnWithValues.kt | 30 +-- .../commonMain/kotlin/naksha/psql/PgRows.kt | 196 +++++++++--------- .../kotlin/naksha/psql/PgWriterDelete.kt | 13 +- .../kotlin/naksha/psql/PgWriterInsert.kt | 2 +- .../kotlin/naksha/psql/PgWriterUpdate.kt | 14 +- .../kotlin/naksha/psql/PgWriterUpsert.kt | 8 +- .../kotlin/naksha/psql/PgTestBase.kt | 2 +- 15 files changed, 156 insertions(+), 161 deletions(-) diff --git a/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/Proxy.kt b/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/Proxy.kt index c71216ef0..751248a71 100644 --- a/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/Proxy.kt +++ b/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/Proxy.kt @@ -265,7 +265,7 @@ abstract class Proxy : PlatformObject { } if (current is PlatformMap) return Platform.proxy(current, AnyObject::class) if (current is PlatformList) return Platform.proxy(current, AnyList::class) - if (current is PlatformDataView) return Platform.proxy(current, DataViewProxy::class) + if (current is Int64) return current.toLong() return current } diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/Index.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/Index.kt index 169b7b1e7..4bed15d03 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/Index.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/Index.kt @@ -18,7 +18,7 @@ import kotlin.js.JsName * collection. The [type] decides the storage method: * - [IndexType.BTREE]: ordered index for equality and range queries on scalar and text columns. * - [IndexType.SPATIAL]: spatial index covering a 2D-encoded geometry column. [on] must contain exactly one geometry member. - * - [IndexType.TAG_MAP]: inverted index over a tags member ([MemberType.TAG_MAP] or [MemberType.TAG_MAP_FROM_ARRAY]) supporting key/value containment queries. [on] must contain exactly one member. + * - [IndexType.TAG_MAP]: inverted index over a tags member ([MemberType.TAG_MAP] or [MemberType.TAG_MAP_FROM_TAG_LIST]) supporting key/value containment queries. [on] must contain exactly one member. * - [IndexType.TAG_LIST]: inverted index over a tag-list member ([MemberType.TAG_LIST]) supporting element containment queries. [on] must contain exactly one member. * * When [internal] is `true` the index is storage-managed (an index the storage maintains itself to keep diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/Int16Member.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/Int16Member.kt index fca0b54f8..9284c0ada 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/Int16Member.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/Int16Member.kt @@ -33,14 +33,14 @@ class Int16Member() : TypedMember() { } /** Retrieves the int16 value of this member from the given feature. */ - fun get(feature: NakshaFeature): Short? = readInt64(feature)?.toShort() + fun get(feature: NakshaFeature): Short? = readLong(feature)?.toShort() /** * Retrieves the int16 value of this member from the given tuple. * TODO: When no such member exists in membersBook, should search along [path] in [tuple.featureBytes], but currently cannot due to JbDecoder2 limits. */ @JsName("getFromTuple") - fun get(tuple: Tuple): Short? = readInt64(tuple)?.toShort() + fun get(tuple: Tuple): Short? = readLong(tuple)?.toShort() /** Sets the int16 value of this member on the given feature. */ fun set(feature: NakshaFeature, value: Short): Any? = setPath(feature, path, value) diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/Int32Member.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/Int32Member.kt index 3cb48349e..7e63de26b 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/Int32Member.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/Int32Member.kt @@ -33,14 +33,14 @@ class Int32Member() : TypedMember() { } /** Retrieves the int32 value of this member from the given feature. */ - fun get(feature: NakshaFeature): Int? = readInt64(feature)?.toInt() + fun get(feature: NakshaFeature): Int? = readLong(feature)?.toInt() /** * Retrieves the int32 value of this member from the given tuple. * TODO: When no such member exists in membersBook, should search along [path] in [tuple.featureBytes], but currently cannot due to JbDecoder2 limits. */ @JsName("getFromTuple") - fun get(tuple: Tuple): Int? = readInt64(tuple)?.toInt() + fun get(tuple: Tuple): Int? = readLong(tuple)?.toInt() /** Sets the int32 value of this member on the given feature. */ fun set(feature: NakshaFeature, value: Int): Any? = setPath(feature, path, value) diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/Int64Member.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/Int64Member.kt index 9288da31d..9178b29ca 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/Int64Member.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/Int64Member.kt @@ -1,6 +1,5 @@ package naksha.model.objects -import naksha.base.Int64 import naksha.model.Tuple import naksha.base.illegalArg import naksha.base.illegalState @@ -34,15 +33,15 @@ class Int64Member() : TypedMember() { } /** Retrieves the int64 value of this member from the given feature. */ - fun get(feature: NakshaFeature): Int64? = readInt64(feature) + fun get(feature: NakshaFeature): Long? = readLong(feature) /** * Retrieves the int64 value of this member from the given tuple. * TODO: When no such member exists in membersBook, should search along [path] in [tuple.featureBytes], but currently cannot due to JbDecoder2 limits. */ @JsName("getFromTuple") - fun get(tuple: Tuple): Int64? = readInt64(tuple) + fun get(tuple: Tuple): Long? = readLong(tuple) /** Sets the int64 value of this member on the given feature. */ - fun set(feature: NakshaFeature, value: Int64): Any? = setPath(feature, path, value) + fun set(feature: NakshaFeature, value: Long): Any? = setPath(feature, path, value) } diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/Int8Member.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/Int8Member.kt index 56f1d9a7d..bb6e959c3 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/Int8Member.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/Int8Member.kt @@ -33,14 +33,14 @@ class Int8Member() : TypedMember() { } /** Retrieves the int8 value of this member from the given feature. */ - fun get(feature: NakshaFeature): Byte? = readInt64(feature)?.toByte() + fun get(feature: NakshaFeature): Byte? = readLong(feature)?.toByte() /** * Retrieves the int8 value of this member from the given tuple. * TODO: When no such member exists in membersBook, should search along [path] in [tuple.featureBytes], but currently cannot due to JbDecoder2 limits. */ @JsName("getFromTuple") - fun get(tuple: Tuple): Byte? = readInt64(tuple)?.toByte() + fun get(tuple: Tuple): Byte? = readLong(tuple)?.toByte() /** Sets the int8 value of this member on the given feature. */ fun set(feature: NakshaFeature, value: Byte): Any? = setPath(feature, path, value) diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/Member.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/Member.kt index 2003af77e..3c1362ecd 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/Member.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/Member.kt @@ -274,11 +274,11 @@ open class Member() : AnyObject(), Comparator { * @param feature The feature to read from. * @return the read value or `null`, if the feature does not store a valid value at the member path. */ - fun readInt64(feature: MapProxy<*,*>): Int64? { + fun readLong(feature: MapProxy<*,*>): Long? { val raw = feature.getPath(path) - if (raw is Int64) return raw - if (raw is Long) return Int64(raw) - if (raw is Number) return Int64(raw.toLong()) + if (raw is Long) return raw + if (raw is Int64) return raw.toLong() + if (raw is Number) return raw.toLong() return null } @@ -390,11 +390,11 @@ open class Member() : AnyObject(), Comparator { * TODO: When no such member exists in membersBook, should search along [path] in [tuple.featureBytes], but currently cannot due to JbDecoder2 limits. */ @JsName("getInt64FromTuple") - fun readInt64(tuple: Tuple): Int64? { + fun readLong(tuple: Tuple): Long? { val raw = tuple.getMember(this) - if (raw is Int64) return raw - if (raw is Long) return Int64(raw) - if (raw is Number) return Int64(raw.toLong()) + if (raw is Int64) return raw.toLong() + if (raw is Long) return raw + if (raw is Number) return raw.toLong() return null } @@ -515,7 +515,7 @@ open class Member() : AnyObject(), Comparator { MemberType.BYTE_ARRAY -> proxy(ByteArrayMember::class) MemberType.TUPLE_NUMBER -> proxy(TupleNumberMember::class) MemberType.SPATIAL -> proxy(SpatialMember::class) - MemberType.TAG_MAP, MemberType.TAG_MAP_FROM_ARRAY -> proxy(TagMapMember::class) + MemberType.TAG_MAP -> proxy(TagMapMember::class) MemberType.TAG_LIST -> proxy(TagListMember::class) else -> this } diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/XyzProcessors.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/XyzProcessors.kt index c26c042f9..733d61784 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/XyzProcessors.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/XyzProcessors.kt @@ -39,8 +39,9 @@ class XyzProcessors private constructor() { @JvmStatic val xyzCreatedAt = IMemberProcessor { _, collection, feature, _, value -> when (value) { - is Int64 -> value - is Number -> Int64(value.toLong()) + is Long -> value + is Int64 -> value.toLong() + is Number -> value.toLong() else -> { val action = collection.useMember(StandardMembers.Tn).readTupleNumber(feature)?.action if (action == Action.CREATE) null else feature.properties.xyz.createdAt @@ -53,7 +54,7 @@ class XyzProcessors private constructor() { * @since 3.0 */ @JvmStatic - val xyzUpdatedAt = IMemberProcessor { _, _, _, _, _ -> Platform.currentMillis() } + val xyzUpdatedAt = IMemberProcessor { _, _, _, _, _ -> Platform.currentMillis().toLong() } /** * Ensures that [XyzAppId][naksha.model.objects.XyzMembers.XyzMembers_C.XyzAppId] is set correctly. @@ -75,7 +76,9 @@ class XyzProcessors private constructor() { */ @JvmStatic val xyzAuthorTimestamp = IMemberProcessor { session, _, _, _, value -> - if (session.options.author != null) Platform.currentMillis() else value as Int64? + if (session.options.author != null) Platform.currentMillis().toLong() + else if (value is Int64) value.toLong() + else value as? Long ?: if (value is Number) value.toLong() else null } /** diff --git a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgColumnWithValues.kt b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgColumnWithValues.kt index 6cd6d6848..033caf0b9 100644 --- a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgColumnWithValues.kt +++ b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgColumnWithValues.kt @@ -2,6 +2,8 @@ package naksha.psql import naksha.base.AnyList import naksha.base.Int64 +import naksha.base.Platform.PlatformCompanion.toJSON +import naksha.model.objects.MemberType /** * Rows as selected in [PgRows]. @@ -31,19 +33,21 @@ internal data class PgColumnWithValues( values.size = size return this } - fun anyValues(): MutableList = values - /** Returns all values of this column as array. */ - fun anyArray(): Array = values.toArray() - fun intValues(): MutableList = values as MutableList - fun intArray(): Array = values.toArray() as Array - fun int64Values(): MutableList = values as MutableList - fun int64Array(): Array = values.toArray() as Array - fun doubleValues(): MutableList = values as MutableList - fun doubleArray(): Array = values.toArray() as Array - fun stringValues(): MutableList = values as MutableList - fun stringArray(): Array = values.toArray() as Array - fun byteArrayValues(): MutableList = values as MutableList - fun byteArrayArray(): Array = values.toArray() as Array + /** + * Returns all values of this column as array that can be feed into PostgresQL [UNNEST](https://www.postgresql.org/docs/18/functions-array.html) function. Requires a minor hack for [naksha.model.TagList]. + * @see PgRows.setRow + * @see PgRows.values + */ + fun toArray(): Array = Array(values.size) { + val value = values[it] + when (pgColumn.memberType) { + // We keep it internally as text[], but UNNEST requires only one value. + // Therefore, we work around by serializing the array into a JSON array, then deserializing after UNNEST. + // See: PgRows.decodedColumns + MemberType.TAG_LIST -> if (value is Array<*>) toJSON(value) else null + else -> value + } + } override fun toString(): String = alias } \ No newline at end of file diff --git a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgRows.kt b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgRows.kt index 79e7c56f7..e5edda67e 100644 --- a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgRows.kt +++ b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgRows.kt @@ -2,7 +2,6 @@ package naksha.psql import naksha.base.AnyList import naksha.base.Int64 -import naksha.base.MapProxy import naksha.geo.SpGeometry import naksha.jbon.BookType import naksha.jbon.HeapBook @@ -10,26 +9,35 @@ import naksha.model.* import naksha.base.NakshaError.NakshaErrorCompanion.ILLEGAL_STATE import naksha.base.NakshaException import naksha.base.Platform.PlatformCompanion.fromJSON -import naksha.base.PlatformList -import naksha.base.PlatformMap +import naksha.base.Platform.PlatformCompanion.toJSON import naksha.base.TupleNumber import naksha.model.objects.MemberType import naksha.base.Version -import naksha.base.illegalArg -import naksha.base.illegalState +import naksha.base.internalError import naksha.base.proxy import naksha.geo.GeoUtil +import naksha.model.objects.MemberType.MemberType_C.BOOLEAN +import naksha.model.objects.MemberType.MemberType_C.BYTE_ARRAY +import naksha.model.objects.MemberType.MemberType_C.FLOAT32 +import naksha.model.objects.MemberType.MemberType_C.FLOAT64 +import naksha.model.objects.MemberType.MemberType_C.INT16 +import naksha.model.objects.MemberType.MemberType_C.INT32 +import naksha.model.objects.MemberType.MemberType_C.INT64 +import naksha.model.objects.MemberType.MemberType_C.INT8 import naksha.model.objects.MemberType.MemberType_C.SPATIAL +import naksha.model.objects.MemberType.MemberType_C.STRING import naksha.model.objects.MemberType.MemberType_C.TAG_LIST import naksha.model.objects.MemberType.MemberType_C.TAG_MAP -import naksha.model.objects.MemberType.MemberType_C.TAG_MAP_FROM_ARRAY +import naksha.model.objects.MemberType.MemberType_C.TUPLE_NUMBER import naksha.model.objects.StandardMembers.StandardMembers_C.FeatureBytes import naksha.model.objects.StandardMembers.StandardMembers_C.Id import naksha.model.objects.StandardMembers.StandardMembers_C.NextVersion import naksha.model.objects.StandardMembers.StandardMembers_C.Tn /** - * Helper class to convert rows into arrays of column-data and vice versa. The main purpose is to read and write full tuples, but it supports basically as well virtual columns. + * Helper class to convert rows into arrays of column-data and vice versa. + * + * The main purpose is to read and write tuples, but it supports basically as well virtual columns. This class translates the correct member [book][naksha.jbon.IBook] _HEAD_ values into what the storage expects. For example, the encoder will place into the member [book][naksha.jbon.IBook] the reference to [TagList] or [TagMap], and this class will know the physical representation. For example a [TagList] need to be encoded as `text[]`, while a [TagMap] need to be encoded as `JSONB`, which effectively is a `JSON` string. This class will do the serialization and deserialization. * @since 3.0 */ internal class PgRows { @@ -203,15 +211,18 @@ internal class PgRows { fun getAny(row: Int, column: PgColumn): Any? = getAny(row, column.name) fun getInt(row: Int, alias: String): Int? = getAny(row, alias) as? Int fun getInt(row: Int, column: PgColumn): Int? = getInt(row, column.name) - fun getInt64(row: Int, alias: String): Int64? = getAny(row, alias) as Int64? - fun getInt64(row: Int, column: PgColumn): Int64? = getInt64(row, column.name) + fun getLong(row: Int, alias: String): Long? = getAny(row, alias) as Long? + fun getLong(row: Int, column: PgColumn): Long? = getLong(row, column.name) fun getDouble(row: Int, alias: String): Double? = getAny(row, alias) as Double? fun getDouble(row: Int, column: PgColumn): Double? = getDouble(row, column.name) fun getString(row: Int, alias: String): String? = getAny(row, alias) as String? fun getString(row: Int, column: PgColumn): String? = getString(row, column.name) fun getByteArray(row: Int, alias: String): ByteArray? = getAny(row, alias) as ByteArray? fun getByteArray(row: Int, column: PgColumn): ByteArray? = getByteArray(row, column.name) + fun getArray(row: Int, alias: String): Array<*>? = getAny(row, alias) as Array<*>? + fun getArray(row: Int, column: PgColumn): Array<*>? = getArray(row, column.name) fun getSpatial(row: Int, alias: String): SpGeometry? { + // Stored as bytea, therefore returned by JDBC as ByteArray. val raw = getByteArray(row, alias) ?: return null return try { Naksha.decodeGeometry(raw) @@ -219,18 +230,27 @@ internal class PgRows { null } } - fun getTags(row: Int, alias: String): TagMap? { + fun getTagMap(row: Int, alias: String): TagMap? { + // Stored as JSONB, therefore returned by JDBC as string. val raw = getString(row, alias) ?: return null return try { - Naksha.decodeTags(raw) + fromJSON(raw).proxy(TagMap::class) } catch (_: Exception) { null } } fun getTagList(row: Int, alias: String): TagList? { - val raw = getString(row, alias) ?: return null + // Stored as text[], therefore returned by JDBC as Array. + val raw = getArray(row, alias) ?: return null return try { - Naksha.decodeTagList(raw) + val tagList = TagList() + tagList.setCapacity(raw.size) + for (tag in raw) { + if (tag !is String) continue + // We know that we read back data we serialized, tags are normalized! + tagList.addTag(tag, false) + } + tagList } catch (_: Exception) { null } @@ -297,20 +317,8 @@ internal class PgRows { membersBook.put(name, raw ?: Version.HEAD.number) } else -> { - val raw = getColumn(name)?.values?.get(row) - val value = when (member.dataType) { - TAG_LIST -> toAnyListOrNull(raw) - SPATIAL -> GeoUtil.fromTWKB(raw as? ByteArray) - TAG_MAP, TAG_MAP_FROM_ARRAY -> when (raw) { - is String -> fromJSON(raw).proxy(TagMap::class) - is TagMap -> raw - null -> null - is MapProxy<*,*> -> raw.proxy(TagMap::class) - is PlatformMap -> raw.proxy(TagMap::class) - else -> throw illegalState("Cannot convert value of type ${raw.let { it::class.simpleName } ?: "null"} to TagMap") - } - else -> raw - } + val pg_value = getColumn(name)?.values?.get(row) + val value = member.dataType.convert(pg_value) membersBook.put(name, value) } } @@ -332,7 +340,9 @@ internal class PgRows { operator fun get(row: Int): Tuple? = getTuple(row) - fun set(row: Int, columnName: String, value: Any?): Boolean { + // TODO: The current usage luckily avoids setting structured types with special encoding. + // However, theoretically we need to handle TagMap and TagList! + fun setColumn(row: Int, columnName: String, value: Any?): Boolean { val column = getColumn(columnName) if (column != null) { setMinRows(row+1) @@ -342,26 +352,37 @@ internal class PgRows { return false } - operator fun set(row: Int, tuple: Tuple) { + operator fun set(row: Int, tuple: Tuple) = setRow(row, tuple) + + fun setRow(row: Int, tuple: Tuple) { setMinRows(row+1) val membersBook = tuple.membersBook val END = membersBook.namesLength() for (i in 0 until END) { val memberName = membersBook.getNameAt(i) ?: continue val column = getColumn(memberName) ?: continue - val value = membersBook[memberName] - column.values[row] = when (column.pgColumn.memberType) { - // Convert any geometry column to TWKB, because the geometry is a bytea in Postgres, but a SpGeometry in the members-book. - SPATIAL -> GeoUtil.toTWKB(value as SpGeometry?) - TAG_MAP_FROM_ARRAY -> when (value) { - null -> null - is TagList -> value.toTagMap() - is ListProxy<*> -> value.proxy(TagList::class).toTagMap() - is TagMap -> value - is PlatformList -> value.proxy(TagList::class).toTagMap() - else -> throw illegalArg("Cannot convert value of type ${value?.let { it::class.simpleName } ?: "null"} to TagMap") - } - else -> value + val member_value = membersBook[memberName] + // Note: The members book is required to contain correctly typed values. + // We convert these values into what is stored in PostgresQL. + column.values[row] = when (val member_type = column.pgColumn.memberType) { + BOOLEAN -> member_value as? Boolean + INT8 -> member_value as? Byte + INT16 -> member_value as? Short + INT32 -> member_value as? Byte + INT64 -> member_value as? Long + FLOAT32 -> member_value as? Float + FLOAT64 -> member_value as? Double + STRING -> member_value as? String + BYTE_ARRAY -> member_value as? ByteArray + // Stored as bytea + TUPLE_NUMBER -> (member_value as? TupleNumber)?.toB256() + // Stored as TWKB bytea + SPATIAL -> if (member_value is SpGeometry) GeoUtil.toTWKB(member_value) else null + // Stored as JSONB string + TAG_MAP -> if (member_value is TagMap) toJSON(member_value) else null + // Stored as text[] + TAG_LIST -> if (member_value is TagList) member_value.toStringArray(true) else null + else -> throw internalError("PgRows: Unknown member type in member book: $member_type") } } // The members-book keeps the tuple-number as a single `_tn` entry; the table splits it into the @@ -424,56 +445,6 @@ internal class PgRows { return this } -// /** -// * Read all rows from cursor, expects the cursor to be at first result and that for each column, there is an array of values, so an aggregate generated via `ARRAY_AGG`. -// * @since 3.0 -// */ -// fun addAggregated(cursor: PgCursor): PgRows { -// if (cursor.isRow()) { -// for (column in columns) { -// if (cursor.contains(column.name)) { -// val values = cursor.column(column.name) -// if (values is Array<*>) { -// withMinRows(values.size) -// for (i in 0 until values.size) { -// set(i, column.name, values[i]) -// } -// } -// } -// } -// } -// return this -// } - -// /** -// * Returns the names of all columns as comma separated string, surrounded with aggregation instruction, _(like `ARRAY_AGG(id)`)_, usage: -// * -// * ```kotlin -// * val rows = PgColumnRows().addColumns(allColumns) -// * val SQL = """SELECT ${rows.aliasesAggregate()} -// * FROM "naksha~admin".${collections.head.quotedName} -// * WHERE id = ANY($1)""" -// * val plan = conn.prepare(SQL, rows.typeNames()) -// * val cursor = plan.execute(rows.valuesExecutable()) -// * ``` -// * -// * @return the aliases of all columns as comma separated string, surrounded with aggregation instruction, example: -// * ```sql -// * ARRAY_AGG("foo") AS "foo", ARRAY_AGG("bar") AS "bar", ... -// * ``` -// * @since 3.0 -// */ -// fun aliasesAggregate(): String { -// val cached = this.namesAggregate -// if (cached != null) return cached -// val names = columns.joinToString(", ") { -// val q = PgUtil.quoteIdent(it.alias) -// "ARRAY_AGG($q) AS $q" -// } -// this.namesAggregate = names -// return names -// } - /** * Returns the aliases of all columns as comma separated string, optionally quoted. * @return the aliases of all columns as comma separated string. @@ -492,7 +463,7 @@ internal class PgRows { * * ```kotlin * val sql = """WITH new_row AS ( - * SELECT * FROM UNNEST(${rows.placeholders()}) + * SELECT ${rows.decodedColumns()} FROM UNNEST(${rows.placeholders()}) * AS t(${rows.names()}) * ) * INSERT INTO ${collection.head.quotedName} (${rows.aliases()}) @@ -503,6 +474,10 @@ internal class PgRows { * * @return the placeholders of all columns as comma separated string. * @since 3.0 + * @see decodedColumns + * @see placeholders + * @see typeNames + * @see values */ fun placeholders(): String { var placeholders = this.placeholders @@ -523,7 +498,7 @@ internal class PgRows { * * ```kotlin * val sql = """WITH new_row AS ( - * SELECT * FROM UNNEST(${rows.placeholders()}) + * SELECT ${rows.decodedColumns()} FROM UNNEST(${rows.placeholders()}) * AS t(${rows.names()}) * ) * INSERT INTO ${collection.head.quotedName} (${rows.aliases()}) @@ -533,6 +508,10 @@ internal class PgRows { * ``` * @return the array type-names of all columns. * @since 3.0 + * @see decodedColumns + * @see placeholders + * @see typeNames + * @see values */ fun typeNames(): Array = Array(columns.size) { val col = columns[it].pgColumn @@ -541,15 +520,22 @@ internal class PgRows { else col.pgType.text + "[]" } - fun newRowProjection(): String = columns.joinToString(", ") { + /** + * Used by [PgWriterInsert], [PgWriterUpdate], and [PgWriterUpsert]. This method returns the columns with some decode hacks when send to the storage as array and decoded using `unnest`. + * @see decodedColumns + * @see placeholders + * @see typeNames + * @see values + */ + fun decodedColumns(): String = columns.joinToString(", ") { val ident = PgUtil.quoteIdent(it.alias) when (it.pgColumn.memberType) { - TAG_LIST -> { - "CASE WHEN $ident IS NULL THEN NULL ELSE ARRAY(SELECT json_array_elements_text($ident::json)) END AS $ident" - } - TAG_MAP, TAG_MAP_FROM_ARRAY -> { - "$ident::jsonb" - } + // We have serialized the text[] as JSON to workaround UNNEST limits. + // When selecting from the UNNEST we need to restore the text[] fron the JSON. + TAG_LIST -> "(CASE WHEN $ident IS NULL THEN NULL ELSE ARRAY(SELECT json_array_elements_text($ident::json)) END)::text[] AS $ident" + // We serialized to String, but PostgresQL expects JSONB, a simple cast does the trick. + TAG_MAP -> "$ident::jsonb" + // The rest is as PostgresQL expects it. else -> ident } } @@ -559,7 +545,7 @@ internal class PgRows { * * ```kotlin * val sql = """WITH new_row AS ( - * SELECT * FROM UNNEST(${rows.placeholders()}) + * SELECT ${rows.decodedColumns()} FROM UNNEST(${rows.placeholders()}) * AS t(${rows.names()}) * ) * INSERT INTO ${collection.head.quotedName} (${rows.aliases()}) @@ -570,7 +556,11 @@ internal class PgRows { * Beware that the array really is two-dimensional: `Array>`. * @return the values of all columns as `Array`. * @since 3.0 + * @see decodedColumns + * @see placeholders + * @see typeNames + * @see values */ @Suppress("UNCHECKED_CAST") - fun values(): Array = Array(columns.size) { columns[it].anyArray() } as Array + fun values(): Array = Array(columns.size) { columns[it].toArray() } as Array } diff --git a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgWriterDelete.kt b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgWriterDelete.kt index 80d2acfb5..29d1be7d8 100644 --- a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgWriterDelete.kt +++ b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgWriterDelete.kt @@ -4,7 +4,6 @@ import naksha.base.Platform import naksha.base.Platform.PlatformCompanion.logger import naksha.base.PlatformUtil import naksha.base.TupleNumber -import naksha.base.Version import naksha.base.conflict import naksha.model.objects.MemberType import naksha.psql.PgColumn.PgColumn_C.FnColumn @@ -43,8 +42,8 @@ internal class PgWriterDelete( var row = 0 for (i in start until end) { val pgWrite = pgWrites[i] - inRows.set(row, FnColumn.ident, pgWrite.featureNumber) - inRows.set(row, "expected_version", pgWrite.version?.number) + inRows.setColumn(row, FnColumn.ident, pgWrite.featureNumber) + inRows.setColumn(row, "expected_version", pgWrite.version?.number) row++ } check(row == (end-start)) @@ -195,7 +194,7 @@ ${if (purge) "LEFT JOIN head_deleted ON head_deleted.$FnColumn = query.$FnColumn // `existing_fn` and `existing_version` are existing rows in HEAD, no matter in what state. // val existing_fn = outRows.getInt64(row, "existing_fn") - val existing_version = outRows.getInt64(row, "existing_version") + val existing_version = outRows.getLong(row, "existing_version") // `head_row` selects features that are not in DELETE state and match the expected version. // These are the actual rows the query act upon. @@ -203,7 +202,7 @@ ${if (purge) "LEFT JOIN head_deleted ON head_deleted.$FnColumn = query.$FnColumn // It is NULL: // - If the feature exists, but is DELETE // - If the feature exists, but the client provided `expected_version` and the head_row.`version` differs. - val head_row_version = outRows.getInt64(row, "head_row_version") + val head_row_version = outRows.getLong(row, "head_row_version") if (head_row_version == null) { // Nothing was done. This can indicate an error, but not in 100% of the cases. @@ -232,8 +231,8 @@ ${if (purge) "LEFT JOIN head_deleted ON head_deleted.$FnColumn = query.$FnColumn val tuple = outRows[row] if (tuple != null) pgWrite.tuple = tuple - val tombstone_fn = outRows.getInt64(row, FnColumn) - val tombstone_version = outRows.getInt64(row, VersionColumn) + val tombstone_fn = outRows.getLong(row, FnColumn) + val tombstone_version = outRows.getLong(row, VersionColumn) pgWrite.tupleNumber = if (tombstone_fn != null && tombstone_version != null) { TupleNumber(storageNumber, catalogNumber, collectionNumber, tombstone_fn, tombstone_version) } else null diff --git a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgWriterInsert.kt b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgWriterInsert.kt index 43b396bf0..ede96d026 100644 --- a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgWriterInsert.kt +++ b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgWriterInsert.kt @@ -33,7 +33,7 @@ internal class PgWriterInsert( private fun plan(conn: PgConnection): PgWriterPlan { val new_row = """WITH new_row AS ( - SELECT ${inRows.newRowProjection()} FROM UNNEST(${inRows.placeholders()}) AS t(${inRows.aliases()}) + SELECT ${inRows.decodedColumns()} FROM UNNEST(${inRows.placeholders()}) AS t(${inRows.aliases()}) )""" // Detect any existing tombstone in HEAD for the same id (auto-purge target). diff --git a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgWriterUpdate.kt b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgWriterUpdate.kt index f39aebe96..d6e90154b 100644 --- a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgWriterUpdate.kt +++ b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgWriterUpdate.kt @@ -38,14 +38,14 @@ internal class PgWriterUpdate( loadAllTuple { row, tuple, pgWrite -> writeByFn[tuple.tupleNumber.featureNumber] = pgWrite // Separate column for the expected HEAD version. - inRows.set(row, "expected_version", pgWrite.version?.number) + inRows.setColumn(row, "expected_version", pgWrite.version?.number) } } private fun plan(conn: PgConnection): PgWriterPlan { // All input provided by client (the updates) val query = """WITH new_row AS ( - SELECT ${inRows.newRowProjection()} FROM UNNEST(${inRows.placeholders()}) AS t(${inRows.aliases()}) + SELECT ${inRows.decodedColumns()} FROM UNNEST(${inRows.placeholders()}) AS t(${inRows.aliases()}) )""" // Select rows from HEAD that we want to update, lock the rows for update @@ -157,26 +157,26 @@ LEFT JOIN inserted ON inserted.$FnColumn = new_row.$FnColumn cursor.fetch().use { outRows.readAll(cursor) for (row in 0 until outRows.size) { - val fn = outRows.getInt64(row, FnColumn) ?: throw illegalState("Column '$FnColumn' in result must not be null") - val version = outRows.getInt64(row, VersionColumn) ?: throw illegalState("Column '$VersionColumn' in result must not be null") + val fn = outRows.getLong(row, FnColumn) ?: throw illegalState("Column '$FnColumn' in result must not be null") + val version = outRows.getLong(row, VersionColumn) ?: throw illegalState("Column '$VersionColumn' in result must not be null") val newTn = TupleNumber(storageNumber, catalogNumber, collectionNumber, fn, version) val pgWrite = writeByFn[fn] ?: throw illegalState("Missing write record for feature-number: $fn") val expected_version: Int64? = pgWrite.version?.number // Feature should have existed. - val existing_fn = outRows.getInt64(row, "_existing_fn") + val existing_fn = outRows.getLong(row, "_existing_fn") ?: throw featureNotFound("Failed to update feature '${pgWrite.id}', no such feature exists") if (existing_fn != fn) { // We do not expect this to ever happen! throw generalException("Internal error, feature-number mismatch for feature '${pgWrite.id}', expected fn: $fn, existing fn: $existing_fn") } - val existing_version = outRows.getInt64(row, "_existing_version") + val existing_version = outRows.getLong(row, "_existing_version") // We do not expect this to ever happen, when we have an existing_fn there must be as well an existing_version! ?: throw generalException("Internal error, missing existing version for feature '${pgWrite.id}' in result-set") val previousTupleNumber = TupleNumber(storageNumber, catalogNumber, collectionNumber, existing_fn, existing_version) // We should have updated the feature - val inserted_fn = outRows.getInt64(row, "_inserted_fn") ?: { + val inserted_fn = outRows.getLong(row, "_inserted_fn") ?: { // The only defined reason is that the expected version did not match. if (expected_version != null && (expected_version and Int64(-4)) != (existing_version and Int64(-4))) { throw conflict("Atomic update failed, feature '${pgWrite.id}' was expected in version $existing_version, but found to be in $existing_version") diff --git a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgWriterUpsert.kt b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgWriterUpsert.kt index 7874a3d48..041288cb3 100644 --- a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgWriterUpsert.kt +++ b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgWriterUpsert.kt @@ -38,7 +38,7 @@ internal class PgWriterUpsert( private fun plan(conn: PgConnection): PgWriterPlan { // This is what we should INSERT or UPDATE. val new_row = """WITH new_row AS ( - SELECT ${inRows.newRowProjection()} FROM UNNEST(${inRows.placeholders()}) AS t(${inRows.aliases()}) + SELECT ${inRows.decodedColumns()} FROM UNNEST(${inRows.placeholders()}) AS t(${inRows.aliases()}) )""" // Select existing. @@ -193,12 +193,12 @@ ${if (head_to_history.isNotEmpty()) "LEFT JOIN head_to_history ON head_to_histor cursor.fetch().use { outRows.readAll(cursor) for (row in 0 until outRows.size) { - val updated_fn = outRows.getInt64(row, "_updated_fn") - val updated_version = outRows.getInt64(row, "_updated_version") + val updated_fn = outRows.getLong(row, "_updated_fn") + val updated_version = outRows.getLong(row, "_updated_version") if (updated_fn != null && updated_version != null) { // UPDATE was executed. val pgWrite = writeByFn[updated_fn] ?: throw generalException("Received _updated_fn '$updated_fn', but found no matching PgWrite") - val previousVersion = outRows.getInt64(row, "_head_row_version") + val previousVersion = outRows.getLong(row, "_head_row_version") ?: throw generalException("Missing previous HEAD version for updated feature '${pgWrite.id}'") val updatedTupleNumber = TupleNumber(storageNumber, catalogNumber, collectionNumber, updated_fn, updated_version) val previousTupleNumber = TupleNumber(storageNumber, catalogNumber, collectionNumber, updated_fn, previousVersion) diff --git a/here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/PgTestBase.kt b/here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/PgTestBase.kt index 9550e6c5b..4debf65fb 100644 --- a/here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/PgTestBase.kt +++ b/here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/PgTestBase.kt @@ -80,7 +80,7 @@ abstract class PgTestBase( @Suppress("DEPRECATION") private fun ensureCatalogId(catalogId: String?): String = NakshaIdType.CATALOG.verify(when (catalogId) { null -> TEST_MAP_ID - "" -> defaultName + "" -> TEST_MAP_ID else -> catalogId }) From 5baff82df97c2da0035aca9263b17fef88fbf05d Mon Sep 17 00:00:00 2001 From: Alexander Lowey-Weber Date: Mon, 31 Aug 2026 10:12:26 +0200 Subject: [PATCH 23/41] Replace Int64 with Long Signed-off-by: Alexander Lowey-Weber --- .../com/here/naksha/app/common/ApiTest.java | 3 +- .../naksha/app/common/FeatureMetadata.java | 4 +- .../naksha/app/service/util/TupleInfo.java | 11 +-- .../storages/GeneratingStorageService.java | 6 +- .../copy/service/CopyServiceTestUtils.java | 3 +- .../activitylog/ActivityLogComparator.java | 2 +- .../activitylog/ActivityLogEnhancer.java | 4 +- .../activitylog/ActivityLogHandler.java | 2 +- .../activitylog/ActivityLogHandlerTest.java | 26 +++--- .../naksha/handler/activitylog/GuidUtil.java | 7 +- .../activitylog/NakshaFeatureBuilder.java | 5 +- .../commonMain/kotlin/naksha/base/Action.kt | 3 +- .../kotlin/naksha/base/AtomicInt64.kt | 12 +-- .../commonMain/kotlin/naksha/base/Binary.kt | 10 +- .../kotlin/naksha/base/BinaryView.kt | 10 +- .../commonMain/kotlin/naksha/base/Epoch.kt | 6 +- .../commonMain/kotlin/naksha/base/Fnv1a64.kt | 46 +++++----- .../kotlin/naksha/base/Int64List.kt | 5 +- .../commonMain/kotlin/naksha/base/JsEnum.kt | 9 +- .../commonMain/kotlin/naksha/base/LibBase.kt | 61 ++----------- .../commonMain/kotlin/naksha/base/Platform.kt | 44 ++++----- .../kotlin/naksha/base/PlatformDataViewApi.kt | 4 +- .../kotlin/naksha/base/PlatformLock.kt | 4 +- .../kotlin/naksha/base/PlatformUtil.kt | 18 ++-- .../commonMain/kotlin/naksha/base/Proxy.kt | 17 ++-- .../kotlin/naksha/base/Timestamp.kt | 12 +-- .../kotlin/naksha/base/TupleNumber.kt | 34 +++---- .../commonMain/kotlin/naksha/base/Version.kt | 88 ++++++++---------- .../kotlin/naksha/base/Fnv1aTest.kt | 6 +- .../kotlin/naksha/base/Int64Test.kt | 61 ++++++------- .../kotlin/naksha/base/PlatformTest.kt | 10 +- .../kotlin/naksha/base/JsAtomicInt64.kt | 14 +-- .../src/jsMain/kotlin/naksha/base/JsInt64.kt | 4 +- .../src/jsMain/kotlin/naksha/base/JsLock.kt | 4 +- .../src/jsMain/kotlin/naksha/base/Platform.kt | 87 +++++++----------- .../kotlin/naksha/base/PlatformDataViewApi.kt | 6 +- .../jvmMain/java/naksha/base/JvmParser.java | 4 +- .../kotlin/naksha/base/CustomDeserializer.kt | 11 +-- .../kotlin/naksha/base/JvmAtomicInt64.kt | 20 ++-- .../jvmMain/kotlin/naksha/base/JvmDataView.kt | 12 +-- .../jvmMain/kotlin/naksha/base/JvmInt64.kt | 34 ++++--- .../src/jvmMain/kotlin/naksha/base/JvmLock.kt | 9 +- .../jvmMain/kotlin/naksha/base/Platform.kt | 54 ++++------- .../kotlin/naksha/base/PlatformDataViewApi.kt | 6 +- .../lib/handlers/DefaultStorageHandler.java | 3 +- .../here/naksha/lib/heapcache/HeapCache.java | 3 +- .../lib/hub/storages/NHAdminStorage.java | 3 +- .../lib/hub/storages/NHSpaceStorage.java | 3 +- .../here/naksha/lib/hub/mock/NHAdminMock.java | 3 +- .../kotlin/naksha/jbon/DictEntry.kt | 4 +- .../commonMain/kotlin/naksha/jbon/HeapBook.kt | 9 +- .../commonMain/kotlin/naksha/jbon/IBook.kt | 9 +- .../kotlin/naksha/jbon/IDictBuilder.kt | 4 +- .../kotlin/naksha/jbon/JbDecoder.kt | 18 ++-- .../kotlin/naksha/jbon/JbDecoder2.kt | 2 +- .../kotlin/naksha/jbon/JbDictionary.kt | 7 +- .../kotlin/naksha/jbon/JbEncoder.kt | 11 +-- .../kotlin/naksha/jbon/JbEncoder2.kt | 23 +++-- .../kotlin/naksha/jbon/NakshaTxn.kt | 26 +++--- .../kotlin/naksha/jbon/NakshaUuid.kt | 9 +- .../kotlin/naksha/jbon/NkStorageRow.kt | 3 +- .../kotlin/naksha/jbon/XyzVersion.kt | 9 +- .../kotlin/naksha/jbon/JbCoreTest.kt | 6 +- .../kotlin/naksha/jbon/Jbon2Test.kt | 52 +++++------ .../kotlin/naksha/jbon/Jbon2MembersTest.kt | 5 +- .../kotlin/naksha/model/AbstractStorage.kt | 18 ++-- .../kotlin/naksha/model/BinaryUtil.kt | 17 ++-- .../kotlin/naksha/model/IStorage.kt | 5 +- .../kotlin/naksha/model/ITupleCache.kt | 7 +- .../kotlin/naksha/model/LibModel.kt | 12 +-- .../commonMain/kotlin/naksha/model/Naksha.kt | 38 ++++---- .../kotlin/naksha/model/NakshaContext.kt | 4 +- .../kotlin/naksha/model/NakshaVersion.kt | 6 +- .../commonMain/kotlin/naksha/model/PgTx.kt | 7 +- .../kotlin/naksha/model/SessionOptions.kt | 4 +- .../kotlin/naksha/model/StoreNumberBits.kt | 9 +- .../kotlin/naksha/model/StreamInfo.kt | 6 +- .../commonMain/kotlin/naksha/model/TagMap.kt | 3 +- .../commonMain/kotlin/naksha/model/Tuple.kt | 38 +++----- .../kotlin/naksha/model/TupleCache.kt | 19 ++-- .../kotlin/naksha/model/TupleHeapCache.kt | 7 +- .../naksha/model/TupleNumberBinaryArray.kt | 13 ++- .../kotlin/naksha/model/TupleNumberList.kt | 7 +- .../commonMain/kotlin/naksha/model/XyzNs.kt | 16 ++-- .../kotlin/naksha/model/mom/MomDeltaNs.kt | 9 +- .../kotlin/naksha/model/objects/Member.kt | 3 - .../kotlin/naksha/model/objects/MemberType.kt | 15 ++- .../naksha/model/objects/NakshaCatalog.kt | 5 +- .../naksha/model/objects/NakshaCollection.kt | 16 ++-- .../naksha/model/objects/NakshaStorage.kt | 6 +- .../model/objects/NakshaSubscriptionState.kt | 2 +- .../kotlin/naksha/model/objects/NakshaTx.kt | 20 ++-- .../naksha/model/objects/XyzProcessors.kt | 3 - .../naksha/model/request/ReadFeatures.kt | 39 ++------ .../kotlin/naksha/model/request/Write.kt | 22 ++--- .../request/notification/NotificationAck.kt | 5 +- .../request/notification/NotificationError.kt | 5 +- .../model/request/notification/TuplesByTxn.kt | 3 +- .../naksha/model/AbstractStorageTest.kt | 19 ++-- .../kotlin/naksha/model/GuidTest.kt | 7 +- .../kotlin/naksha/model/MemberTest.kt | 1 - .../naksha/model/NakshaCollectionProxyTest.kt | 5 +- .../kotlin/naksha/model/NakshaTest.kt | 91 +++++++++---------- .../naksha/model/TransactionNumberTest.kt | 5 +- .../kotlin/naksha/model/TupleNumberTest.kt | 9 +- .../kotlin/naksha/model/TupleHeapCache.js.kt | 7 +- .../kotlin/naksha/model/TupleHeapCache.jvm.kt | 9 +- .../kotlin/naksha/model/PropertyFilterTest.kt | 7 +- .../naksha/psql/JbNakshaCollectionDecoder.kt | 13 ++- .../kotlin/naksha/psql/PgAdminCatalog.kt | 29 +++--- .../kotlin/naksha/psql/PgCatalog.kt | 4 +- .../kotlin/naksha/psql/PgCollection.kt | 2 +- .../kotlin/naksha/psql/PgColumnWithValues.kt | 3 +- .../kotlin/naksha/psql/PgConnection.kt | 5 +- .../kotlin/naksha/psql/PgHeadTable.kt | 5 +- .../kotlin/naksha/psql/PgHistoryPartition.kt | 7 +- .../kotlin/naksha/psql/PgHistoryTable.kt | 7 +- .../commonMain/kotlin/naksha/psql/PgLock.kt | 5 +- .../commonMain/kotlin/naksha/psql/PgQuery.kt | 5 +- .../kotlin/naksha/psql/PgQueryBuilder.kt | 7 +- .../kotlin/naksha/psql/PgQueryWhereBuilder.kt | 16 ++-- .../commonMain/kotlin/naksha/psql/PgReader.kt | 4 +- .../commonMain/kotlin/naksha/psql/PgRows.kt | 15 ++- .../kotlin/naksha/psql/PgSession.kt | 9 +- .../commonMain/kotlin/naksha/psql/PgTxn.kt | 7 +- .../commonMain/kotlin/naksha/psql/PgType.kt | 7 +- .../commonMain/kotlin/naksha/psql/PgUtil.kt | 4 +- .../commonMain/kotlin/naksha/psql/PgWrite.kt | 8 +- .../kotlin/naksha/psql/PgWriterBase.kt | 3 +- .../kotlin/naksha/psql/PgWriterUpdate.kt | 9 +- .../kotlin/naksha/psql/PgWriterUpsert.kt | 3 +- .../kotlin/naksha/psql/ChainCollectionTest.kt | 37 ++++---- .../kotlin/naksha/psql/DeleteFeatureBase.kt | 5 +- .../kotlin/naksha/psql/InsertFeatureTest.kt | 5 +- .../psql/MemberValueMaterializationTest.kt | 2 - .../naksha/psql/ReadFeaturesByOtherTns.kt | 5 +- .../kotlin/naksha/psql/UpdateFeatureTest.kt | 7 +- .../kotlin/naksha/psql/UpgradeStorageTest.kt | 5 +- .../kotlin/naksha/psql/Plv8Connection.kt | 5 +- .../jsMain/kotlin/naksha/psql/Plv8Trigger.kt | 13 ++- .../kotlin/naksha/psql/PsqlAdminCatalog.kt | 10 +- .../kotlin/naksha/psql/PsqlConnection.kt | 5 +- .../jvmMain/kotlin/naksha/psql/PsqlCursor.kt | 14 +-- .../kotlin/naksha/psql/PsqlInstance.kt | 8 +- .../jvmMain/kotlin/naksha/psql/PsqlQuery.kt | 18 +--- .../naksha/lib/view/ViewLayerCollection.java | 2 +- .../concurrent/ParallelQueryExecutor.java | 4 +- .../java/com/here/naksha/lib/view/Sample.java | 3 +- .../merge/MergeByStoragePriorityTest.java | 1 - .../here/naksha/storage/http/HttpStorage.java | 3 +- .../ConnectorInterfaceWriteExecute.java | 7 +- 151 files changed, 809 insertions(+), 1086 deletions(-) diff --git a/here-naksha-app-service/src/jvmTest/java/com/here/naksha/app/common/ApiTest.java b/here-naksha-app-service/src/jvmTest/java/com/here/naksha/app/common/ApiTest.java index ef67e369a..1edff63e3 100644 --- a/here-naksha-app-service/src/jvmTest/java/com/here/naksha/app/common/ApiTest.java +++ b/here-naksha-app-service/src/jvmTest/java/com/here/naksha/app/common/ApiTest.java @@ -20,7 +20,6 @@ import java.util.concurrent.atomic.AtomicBoolean; -import naksha.base.Int64; import naksha.model.Naksha; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.extension.ExtendWith; @@ -54,7 +53,7 @@ public NakshaTestWebClient getNakshaClient() { public static String databaseId; /** The number of the storage. */ - public static Int64 databaseNumber; + public static long databaseNumber; /** The identifier of the data catalog. */ public static String catalogId; diff --git a/here-naksha-app-service/src/jvmTest/java/com/here/naksha/app/common/FeatureMetadata.java b/here-naksha-app-service/src/jvmTest/java/com/here/naksha/app/common/FeatureMetadata.java index 125626a20..2eb364968 100644 --- a/here-naksha-app-service/src/jvmTest/java/com/here/naksha/app/common/FeatureMetadata.java +++ b/here-naksha-app-service/src/jvmTest/java/com/here/naksha/app/common/FeatureMetadata.java @@ -19,8 +19,8 @@ public static FeatureMetadata from(NakshaFeature feature) { return new FeatureMetadata( feature.getId(), xyzNamespace.getUuid(), - xyzNamespace.getCreatedAt().toLong(), - xyzNamespace.getUpdatedAt().toLong() + xyzNamespace.getCreatedAt(), + xyzNamespace.getUpdatedAt() ); } diff --git a/here-naksha-app-service/src/jvmTest/java/com/here/naksha/app/service/util/TupleInfo.java b/here-naksha-app-service/src/jvmTest/java/com/here/naksha/app/service/util/TupleInfo.java index 8068f5b96..d807d41f9 100644 --- a/here-naksha-app-service/src/jvmTest/java/com/here/naksha/app/service/util/TupleInfo.java +++ b/here-naksha-app-service/src/jvmTest/java/com/here/naksha/app/service/util/TupleInfo.java @@ -1,15 +1,12 @@ package com.here.naksha.app.service.util; import com.here.naksha.app.common.ApiTest; -import naksha.base.Int64; import naksha.base.Action; import naksha.model.Naksha; import naksha.base.TupleNumber; import naksha.base.Version; import org.jetbrains.annotations.NotNull; -import static naksha.base.Platform.longToInt64; - public final class TupleInfo { /** * Create a new collection test info from the given collection identifier, using {@link ApiTest} static values for database and catalog. @@ -43,7 +40,7 @@ public TupleInfo(@NotNull String databaseId, @NotNull String catalogId, @NotNull public final @NotNull String databaseId; public final @NotNull String catalogId; public final @NotNull String collectionId; - public final @NotNull Int64 databaseNumber; + public final long databaseNumber; public final int catalogNumber; public final int collectionNumber; @@ -56,8 +53,8 @@ public TupleInfo(@NotNull String databaseId, @NotNull String catalogId, @NotNull * @return the new unique virtual tuple-number. */ public @NotNull TupleNumber newTupleNumber(@NotNull String featureId, @NotNull Action action) { - final Version version = Version.now(longToInt64(seq++), action); - final Int64 featureNumber = Naksha.featureNumber(featureId); + final Version version = Version.now(seq++, action); + final long featureNumber = Naksha.featureNumber(featureId); return new TupleNumber(databaseNumber, catalogNumber, collectionNumber, featureNumber, version.number); } -} \ No newline at end of file +} diff --git a/here-naksha-cli/src/jvmMain/java/com/here/naksha/cli/storages/GeneratingStorageService.java b/here-naksha-cli/src/jvmMain/java/com/here/naksha/cli/storages/GeneratingStorageService.java index c35a67b04..5c58f76c4 100644 --- a/here-naksha-cli/src/jvmMain/java/com/here/naksha/cli/storages/GeneratingStorageService.java +++ b/here-naksha-cli/src/jvmMain/java/com/here/naksha/cli/storages/GeneratingStorageService.java @@ -3,8 +3,6 @@ import com.here.naksha.lib.core.models.geojson.WebMercatorTile; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; -import naksha.base.Int64; -import naksha.base.Platform; import naksha.base.TupleNumber; import naksha.base.Version; import naksha.geo.LineStringCoord; @@ -25,12 +23,12 @@ final class GeneratingStorageService { private final AtomicInteger tileIndex = new AtomicInteger(0); @NotNull - FeatureTupleList generateDummyFeatureTuples(Int64 storageNumber, int numOfTuplesToGenerate) { + FeatureTupleList generateDummyFeatureTuples(long storageNumber, int numOfTuplesToGenerate) { FeatureTupleList dummyFeatureTuples = new FeatureTupleList(); dummyFeatureTuples.setCapacity(numOfTuplesToGenerate); for (int i = 0; i < numOfTuplesToGenerate; ++i) { TupleNumber dummyTupleNumber = new TupleNumber( - storageNumber, 0, 0, Platform.intToInt64(0), Version.HEAD.number + storageNumber, 0, 0, 0L, Version.HEAD.number ); FeatureTuple dummyFeatureTuple = new FeatureTuple(dummyTupleNumber, null); dummyFeatureTuples.add(dummyFeatureTuple); diff --git a/here-naksha-cli/src/jvmTest/java/com/here/naksha/cli/copy/service/CopyServiceTestUtils.java b/here-naksha-cli/src/jvmTest/java/com/here/naksha/cli/copy/service/CopyServiceTestUtils.java index 0fff7c7ee..67607385a 100644 --- a/here-naksha-cli/src/jvmTest/java/com/here/naksha/cli/copy/service/CopyServiceTestUtils.java +++ b/here-naksha-cli/src/jvmTest/java/com/here/naksha/cli/copy/service/CopyServiceTestUtils.java @@ -1,6 +1,5 @@ package com.here.naksha.cli.copy.service; -import naksha.base.Platform; import naksha.model.ISession; import naksha.model.IStorage; import naksha.model.IWriteSession; @@ -44,7 +43,7 @@ public static FeatureTupleList nakshaFeatureListToFeatureTupleList(List tupleNumbers) { - // next_version is a plain int8 column, so we pass an Int64[] of the version values. + // next_version is a plain int8 column, so we pass Long version values. final Or or = new Or(); final OpList orClauses = or.getChildren(); for (TupleNumber tupleNumber : tupleNumbers) { diff --git a/here-naksha-handler-activitylog/src/jvmTest/java/com/here/naksha/handler/activitylog/ActivityLogHandlerTest.java b/here-naksha-handler-activitylog/src/jvmTest/java/com/here/naksha/handler/activitylog/ActivityLogHandlerTest.java index 591f17ec6..3f8daa54e 100644 --- a/here-naksha-handler-activitylog/src/jvmTest/java/com/here/naksha/handler/activitylog/ActivityLogHandlerTest.java +++ b/here-naksha-handler-activitylog/src/jvmTest/java/com/here/naksha/handler/activitylog/ActivityLogHandlerTest.java @@ -29,8 +29,6 @@ import java.util.Map; import java.util.stream.Stream; import naksha.base.AnyList; -import naksha.base.Int64; -import naksha.base.JvmInt64; import naksha.base.Timestamp; import naksha.base.Action; import naksha.base.Guid; @@ -69,8 +67,8 @@ class ActivityLogHandlerTest { private static final String SPACE_ID = "test_activity_space"; - private static final JvmInt64 T0 = new JvmInt64(1749477141945L); - private static final JvmInt64 T1 = new JvmInt64(1749477141955L); + private static final long T0 = 1749477141945L; + private static final long T1 = 1749477141955L; @Mock INaksha naksha; @@ -160,8 +158,8 @@ void shouldImmediatelySucceedOnWriteCollection() { void shouldComposeActivityFeatures() throws Exception { // Given: features uuid String featureId = "featureId"; - Guid initialUuid = guid(featureId, Version.now(new JvmInt64(1),Action.CREATE)); - Guid newUuid = guid(featureId, Version.now(new JvmInt64(2),Action.UPDATE)); + Guid initialUuid = guid(featureId, Version.now(1L, Action.CREATE)); + Guid newUuid = guid(featureId, Version.now(2L, Action.UPDATE)); // And: old version of feature NakshaFeature oldFeature = nakshaFeature(featureId) @@ -232,7 +230,7 @@ void shouldComposeActivityFeatures() throws Exception { void shouldNotCalculateReversePatchAfterCreation() throws Exception { // Given String featureId = "featureId"; - Guid createdGuid = guid(featureId, Version.now(new JvmInt64(0), Action.CREATE)); + Guid createdGuid = guid(featureId, Version.now(0L, Action.CREATE)); // And: space storage that returns only some feature with 'CREATE' action configureSpaceStorage( @@ -265,8 +263,8 @@ void shouldNotCalculateDiffAfterDeletion() throws Exception { String featureId = "featureId"; Timestamp ts0 = Timestamp.fromMillis(T0); Timestamp ts1 = Timestamp.fromMillis(T1); - Version createdVersion = Version.auto(ts0.getYear(), ts0.getMonth(), ts0.getDay(), new JvmInt64(0), Action.CREATE); - Version deletedVersion = Version.auto(ts1.getYear(), ts1.getMonth(), ts1.getDay(), new JvmInt64(1), Action.DELETE); + Version createdVersion = Version.auto(ts0.getYear(), ts0.getMonth(), ts0.getDay(), 0L, Action.CREATE); + Version deletedVersion = Version.auto(ts1.getYear(), ts1.getMonth(), ts1.getDay(), 1L, Action.DELETE); Guid createdGuid = guid(featureId, createdVersion); Guid deletedGuid = guid(featureId, deletedVersion); @@ -467,7 +465,7 @@ private boolean containsNextVersionMetaQuery(ReadFeatures readFeatures, TupleNum Op metaQuery = readFeatures.getQueryMembers(); if (metaQuery instanceof Or or) { OpList orChildren = or.getChildren(); - List versions = new java.util.ArrayList<>(); + List versions = new java.util.ArrayList<>(); if (orChildren.getSize() == 0) return false; for (int i = 0; i < orChildren.getSize(); i++) { Object child = orChildren.get(i); @@ -492,7 +490,7 @@ private boolean containsNextVersionMetaQuery(ReadFeatures readFeatures, TupleNum } Object val = nextEq.getValue(); - if (!(val instanceof Int64 v)) return false; + if (!(val instanceof Long v)) return false; versions.add(v); } @@ -504,13 +502,13 @@ private boolean containsNextVersionMetaQuery(ReadFeatures readFeatures, TupleNum } if (!(metaQuery instanceof IsAnyOf op)) return false; if (!StandardMembers.NextVersion.getName().equals(op.getAt())) return false; - // next_version is an int8 column — the IsAnyOf items hold the Int64 version values. + // next_version is an int8 column, so the IsAnyOf items hold Long version values. AnyList items = op.getItems(); if (expectedTns.length == 0) return items.getSize() > 0; - List versions = new java.util.ArrayList<>(); + List versions = new java.util.ArrayList<>(); for (int i = 0; i < items.getSize(); i++) { Object item = items.get(i); - if (item instanceof Int64 v) versions.add(v); + if (item instanceof Long v) versions.add(v); else return false; } if (versions.size() != expectedTns.length) return false; diff --git a/here-naksha-handler-activitylog/src/jvmTest/java/com/here/naksha/handler/activitylog/GuidUtil.java b/here-naksha-handler-activitylog/src/jvmTest/java/com/here/naksha/handler/activitylog/GuidUtil.java index 7bf4de052..338419019 100644 --- a/here-naksha-handler-activitylog/src/jvmTest/java/com/here/naksha/handler/activitylog/GuidUtil.java +++ b/here-naksha-handler-activitylog/src/jvmTest/java/com/here/naksha/handler/activitylog/GuidUtil.java @@ -1,26 +1,23 @@ package com.here.naksha.handler.activitylog; import java.util.Random; -import naksha.base.JvmInt64; import naksha.base.Action; import naksha.base.Guid; import naksha.base.TupleNumber; import naksha.base.Version; -import static naksha.base.LibBaseKt.Int64; - public final class GuidUtil { private static final Random random = new Random(); private GuidUtil(){} public static Version randomVersion() { - return Version.now(Int64(random.nextLong() & Version.SEQ_MAX.toLong()), Action.VERSION); + return Version.now(random.nextLong() & Version.SEQ_MAX, Action.VERSION); } public static Guid guid(String featureId, Version version) { return new Guid(featureId, new TupleNumber( - new JvmInt64(0), 0, 0, new JvmInt64(0), version.number + 0L, 0, 0, 0L, version.number )); } } diff --git a/here-naksha-handler-activitylog/src/jvmTest/java/com/here/naksha/handler/activitylog/NakshaFeatureBuilder.java b/here-naksha-handler-activitylog/src/jvmTest/java/com/here/naksha/handler/activitylog/NakshaFeatureBuilder.java index 208b2f6fa..b5b57cc83 100644 --- a/here-naksha-handler-activitylog/src/jvmTest/java/com/here/naksha/handler/activitylog/NakshaFeatureBuilder.java +++ b/here-naksha-handler-activitylog/src/jvmTest/java/com/here/naksha/handler/activitylog/NakshaFeatureBuilder.java @@ -8,7 +8,6 @@ import static naksha.model.XyzNs.NUUID; import java.util.Map; -import naksha.base.JvmInt64; import naksha.base.Action; import naksha.model.XyzNs; import naksha.model.objects.NakshaFeature; @@ -59,12 +58,12 @@ NakshaFeatureBuilder withAction(Action action) { return this; } - NakshaFeatureBuilder withCreatedAt(JvmInt64 createdAt) { + NakshaFeatureBuilder withCreatedAt(long createdAt) { feature.getProperties().getXyz().put(CREATED_AT, createdAt); return this; } - NakshaFeatureBuilder withUpdatedAt(JvmInt64 updatedAt) { + NakshaFeatureBuilder withUpdatedAt(long updatedAt) { feature.getProperties().getXyz().put(UPDATED_AT, updatedAt); return this; } diff --git a/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/Action.kt b/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/Action.kt index daa97ffa6..609699101 100644 --- a/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/Action.kt +++ b/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/Action.kt @@ -128,7 +128,7 @@ class Action : JsEnum() { */ @JsStatic @JvmStatic - fun fromVersion(version: Int64): Action = FROM_VALUE[version.toInt() and 3] ?: VERSION + fun fromVersion(version: Long): Action = FROM_VALUE[version.toInt() and 3] ?: VERSION } /** @@ -154,4 +154,3 @@ class Action : JsEnum() { var shortId: String = VERSION_SHORT private set } - diff --git a/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/AtomicInt64.kt b/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/AtomicInt64.kt index 4e56247a3..1445c246f 100644 --- a/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/AtomicInt64.kt +++ b/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/AtomicInt64.kt @@ -12,13 +12,13 @@ interface AtomicInt64 { /** * Returns the current value. */ - fun get(): Int64 + fun get(): Long /** * Sets the current value. * @param value the value to set. */ - fun set(value: Int64) + fun set(value: Long) /** * Set the value, if the current value is the expected. @@ -26,19 +26,19 @@ interface AtomicInt64 { * @param update the new value to set. * @return _true_ if the value was set. */ - fun compareAndSet(expect: Int64, update: Int64): Boolean + fun compareAndSet(expect: Long, update: Long): Boolean /** * Add the given value atomically, return the value before adding. * @param value the value to add atomically to the current one. * @return the value before adding. */ - fun getAndAdd(value: Int64): Int64 + fun getAndAdd(value: Long): Long /** * Add the given value atomically, return the new value. * @param value the value to add atomically to the current one. * @return the new value after adding. */ - fun addAndGet(value: Int64): Int64 -} \ No newline at end of file + fun addAndGet(value: Long): Long +} diff --git a/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/Binary.kt b/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/Binary.kt index 54418c0a4..bc66966ae 100644 --- a/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/Binary.kt +++ b/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/Binary.kt @@ -324,27 +324,27 @@ open class Binary() : BinaryView { end += 4 } - override fun getInt64(pos: Int, littleEndian: Boolean): Int64 { + override fun getInt64(pos: Int, littleEndian: Boolean): Long { prepareRead(pos, 8, byteLength) return dataview_get_int64(view, pos, littleEndian) } - override fun setInt64(pos: Int, value: Int64, littleEndian: Boolean) { + override fun setInt64(pos: Int, value: Long, littleEndian: Boolean) { prepareWrite(pos, 8) dataview_set_int64(view, pos, value, littleEndian) } - override fun readInt64(littleEndian: Boolean): Int64 { + override fun readInt64(littleEndian: Boolean): Long { prepareRead(pos, 8, end) val v = dataview_get_int64(view, pos, littleEndian) pos += 8 return v } - override fun writeInt64(value: Int64, littleEndian: Boolean) { + override fun writeInt64(value: Long, littleEndian: Boolean) { prepareWrite(end, 8) dataview_set_int64(view, end, value, littleEndian) end += 8 } -} \ No newline at end of file +} diff --git a/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/BinaryView.kt b/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/BinaryView.kt index b94c7633b..d2683d2d5 100644 --- a/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/BinaryView.kt +++ b/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/BinaryView.kt @@ -271,7 +271,7 @@ interface BinaryView { * @return The read value. * @throws IndexOutOfBoundsException If the [pos] is at [byteLength] or reading would require to read [byteLength]. */ - fun getInt64(pos: Int, littleEndian: Boolean = false): Int64 + fun getInt64(pos: Int, littleEndian: Boolean = false): Long /** * Writes into the [byteArray]. @@ -279,7 +279,7 @@ interface BinaryView { * @param littleEndian If the data should be stored in [little-endian](https://en.wikipedia.org/wiki/Endianness) in the [byteArray]. * @throws IndexOutOfBoundsException If [resize] is _false_ and the [end] is at [byteLength] or writing would require to write at [byteLength]. */ - fun setInt64(pos: Int, value: Int64, littleEndian: Boolean = false) + fun setInt64(pos: Int, value: Long, littleEndian: Boolean = false) /** * Read from the [byteArray] at [pos] and increment the position. @@ -287,13 +287,13 @@ interface BinaryView { * @return The read value. * @throws IndexOutOfBoundsException If the [pos] is at [end] or reading would require to read [end]. */ - fun readInt64(littleEndian: Boolean = false): Int64 + fun readInt64(littleEndian: Boolean = false): Long /** * Writes into the [byteArray] at [end] and increment the end. * @param littleEndian If the data should be stored in [little-endian](https://en.wikipedia.org/wiki/Endianness) in the [byteArray]. * @throws IndexOutOfBoundsException If [resize] is _false_ and the [end] is at [byteLength] or writing would require to write at [byteLength]. */ - fun writeInt64(value: Int64, littleEndian: Boolean = false) + fun writeInt64(value: Long, littleEndian: Boolean = false) -} \ No newline at end of file +} diff --git a/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/Epoch.kt b/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/Epoch.kt index 2906b612f..47572d5f3 100644 --- a/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/Epoch.kt +++ b/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/Epoch.kt @@ -12,8 +12,8 @@ import kotlin.time.Instant */ @Suppress("OPT_IN_USAGE", "unused") @JsExport -open class Epoch(val millis: Int64 = Platform.currentMillis()) { - private val dateTime = Instant.fromEpochMilliseconds(millis.toLong()).toLocalDateTime(TimeZone.UTC) +open class Epoch(val millis: Long = Platform.currentMillis()) { + private val dateTime = Instant.fromEpochMilliseconds(millis).toLocalDateTime(TimeZone.UTC) /** * The year. @@ -56,4 +56,4 @@ open class Epoch(val millis: Int64 = Platform.currentMillis()) { */ @JvmField val millisOfSecond: Int = dateTime.nanosecond / 1000 -} \ No newline at end of file +} diff --git a/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/Fnv1a64.kt b/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/Fnv1a64.kt index 32d07b537..85e6200a6 100644 --- a/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/Fnv1a64.kt +++ b/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/Fnv1a64.kt @@ -19,12 +19,12 @@ class Fnv1a64 { /** * The multiplier used. */ - private val MUL = Platform.toInt64(1099511628211L) + private const val MUL = 1099511628211L /** * The initial value. */ - private val INITIAL_VALUE = Platform.toInt64(0xCBF29CE484222325uL.toLong()) + private const val INITIAL_VALUE = -3750763034362895579L /** * Reset the hash to the default initial value. @@ -32,7 +32,7 @@ class Fnv1a64 { */ @JvmStatic @JsStatic - fun start(): Int64 = INITIAL_VALUE + fun start(): Long = INITIAL_VALUE /** * Hash the given string. Internally all code-points are hashed by their width, so 8-bit, 16-bit or 24-bit @@ -43,7 +43,7 @@ class Fnv1a64 { */ @JvmStatic @JsStatic - fun string(hashCode: Int64, string: String): Int64 { + fun string(hashCode: Long, string: String): Long { var hash = hashCode var i = 0 while (i < string.length) { @@ -78,8 +78,8 @@ class Fnv1a64 { */ @JvmStatic @JsStatic - fun int8(hashCode: Int64, v: Byte): Int64 { - var hash = hashCode xor Platform.toInt64(v.toInt() and 0xff) + fun int8(hashCode: Long, v: Byte): Long { + var hash = hashCode xor (v.toLong() and 0xff) hash *= MUL return hash } @@ -92,10 +92,10 @@ class Fnv1a64 { */ @JvmStatic @JsStatic - fun int16BE(hashCode: Int64, v: Short): Int64 { - var hash = hashCode xor Int64((v.toInt() and 0xffff) ushr 8) + fun int16BE(hashCode: Long, v: Short): Long { + var hash = hashCode xor ((v.toInt() and 0xffff) ushr 8).toLong() hash *= MUL - hash = hash xor Int64(v.toInt() and 0xff) + hash = hash xor (v.toLong() and 0xff) hash *= MUL return hash } @@ -108,10 +108,10 @@ class Fnv1a64 { */ @JvmStatic @JsStatic - fun int16LE(hashCode: Int64, v: Short): Int64 { - var hash = hashCode xor Int64(v.toInt() and 0xff) + fun int16LE(hashCode: Long, v: Short): Long { + var hash = hashCode xor (v.toLong() and 0xff) hash *= MUL - hash = hash xor Int64((v.toInt() and 0xffff) ushr 8) + hash = hash xor ((v.toInt() and 0xffff) ushr 8).toLong() hash *= MUL return hash } @@ -124,14 +124,14 @@ class Fnv1a64 { */ @JvmStatic @JsStatic - fun int32BE(hashCode: Int64, v: Int): Int64 { - var hash = hashCode xor Int64(v ushr 24) + fun int32BE(hashCode: Long, v: Int): Long { + var hash = hashCode xor (v ushr 24).toLong() hash *= MUL - hash = hash xor Int64((v ushr 16) and 0xff) + hash = hash xor ((v ushr 16) and 0xff).toLong() hash *= MUL - hash = hash xor Int64((v ushr 8) and 0xff) + hash = hash xor ((v ushr 8) and 0xff).toLong() hash *= MUL - hash = hash xor Int64(v and 0xff) + hash = hash xor (v and 0xff).toLong() hash *= MUL return hash } @@ -144,16 +144,16 @@ class Fnv1a64 { */ @JvmStatic @JsStatic - fun int32LE(hashCode: Int64, v: Int): Int64 { - var hash = hashCode xor Int64(v and 0xff) + fun int32LE(hashCode: Long, v: Int): Long { + var hash = hashCode xor (v and 0xff).toLong() hash *= MUL - hash = hash xor Int64((v ushr 8) and 0xff) + hash = hash xor ((v ushr 8) and 0xff).toLong() hash *= MUL - hash = hash xor Int64((v ushr 16) and 0xff) + hash = hash xor ((v ushr 16) and 0xff).toLong() hash *= MUL - hash = hash xor Int64(v ushr 24) + hash = hash xor (v ushr 24).toLong() hash *= MUL return hash } } -} \ No newline at end of file +} diff --git a/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/Int64List.kt b/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/Int64List.kt index 02a912044..83b48ae7c 100644 --- a/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/Int64List.kt +++ b/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/Int64List.kt @@ -8,17 +8,16 @@ import kotlin.js.JsExport * Standard declaration of a list of 64-bit integers. */ @JsExport -open class Int64List : ListProxy(Int64::class) { +open class Int64List : ListProxy(Long::class) { /** * Adds the specified element to the end of this list. * @param element the element to add. * @return this. * @since 3.0 */ - fun append(element: Int64?): Int64List { + fun append(element: Long?): Int64List { super.add(element) return this } } - diff --git a/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/JsEnum.kt b/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/JsEnum.kt index e0f3a8865..999b1bbd5 100644 --- a/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/JsEnum.kt +++ b/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/JsEnum.kt @@ -64,7 +64,7 @@ abstract class JsEnum : CharSequence { private object NULL /** - * The value, either [String], [Int], [Int64], [Double], [Boolean] or _null_. + * The value, either [String], [Int], [Long], [Double], [Boolean] or _null_. */ var value: Any? = null private set @@ -91,8 +91,7 @@ abstract class JsEnum : CharSequence { is Byte -> value.toInt() is Short -> value.toInt() is Int -> value - is Long -> Int64(value) - is Int64 -> value + is Long -> value is String -> value is Float -> value.toDouble() is Double -> value @@ -210,7 +209,7 @@ abstract class JsEnum : CharSequence { @JvmStatic @JsStatic fun def(enumKlass: KClass, value: Any?, init: Fx1? = null): ENUM { - require(value === null || value is String || value is Number || value is Int64) { + require(value === null || value is String || value is Number) { "Invalid enumeration value, require null, String or Number" } val e = __get(value, enumKlass, false) @@ -542,4 +541,4 @@ abstract class JsEnum : CharSequence { final override fun get(index: Int): Char = toString()[index] final override fun subSequence(startIndex: Int, endIndex: Int): CharSequence = toString().subSequence(startIndex, endIndex) -} \ No newline at end of file +} diff --git a/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/LibBase.kt b/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/LibBase.kt index e9fbe4db2..4c12d2ef3 100644 --- a/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/LibBase.kt +++ b/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/LibBase.kt @@ -8,68 +8,25 @@ package naksha.base import kotlin.reflect.KClass import kotlin.reflect.cast -inline fun Int64(value: Long) = Platform.longToInt64(value) -inline fun Int64(value: Int) = Platform.toInt64(value) -inline fun Int64(value: Double, rawBits: Boolean = false) = if (rawBits) Platform.toInt64RawBits(value) else Platform.toInt64(value) -fun asInt64(any: Any?): Int64 = any as Int64 +fun asInt64(any: Any?): Long = any as Long -inline infix fun Short.eq(other: Int64): Boolean = other eq this -inline infix fun Int.eq(other: Int64): Boolean = other eq this -inline infix fun Double.eq(other: Int64): Boolean = other eq this +const val INT_TO_UNSIGNED_INT64_MASK = 0xffff_ffffL -inline operator fun Short.plus(other: Int64): Int64 = other + this -inline operator fun Int.plus(other: Int64): Int64 = other + this -inline operator fun Double.plus(other: Int64): Double = this + Platform.toDouble(other) - -inline operator fun Short.minus(other: Int64): Int64 = other + (-this) -inline operator fun Int.minus(other: Int64): Int64 = other + (-this) -inline operator fun Double.minus(other: Int64): Double = this - Platform.toDouble(other) - -inline operator fun Short.times(other: Int64): Int64 = other * this -inline operator fun Int.times(other: Int64): Int64 = other * this -inline operator fun Double.times(other: Int64): Double = this * Platform.toDouble(other) - -inline operator fun Short.rem(other: Int64): Int64 = Platform.toInt64(this) % other -inline operator fun Int.rem(other: Int64): Int64 = Platform.toInt64(this) % other -inline operator fun Double.rem(other: Int64): Double = this % Platform.toDouble(other) - -inline operator fun Short.div(other: Int64): Int64 = Platform.toInt64(this) / other -inline operator fun Int.div(other: Int64): Int64 = Platform.toInt64(this) / other -inline operator fun Double.div(other: Int64): Double = this / Platform.toDouble(other) - -inline operator fun Short.compareTo(other: Int64): Int { - val diff = this - other - return if (diff eq 0) 0 else if (diff < 0) -1 else 1 -} - -inline operator fun Int.compareTo(other: Int64): Int { - val diff = this - other - return if (diff eq 0) 0 else if (diff < 0) -1 else 1 -} - -inline operator fun Double.compareTo(other: Int64): Int { - val diff = this - other - return if (diff == 0.0) 0 else if (diff <= 0.0) -1 else 1 -} - -val INT_TO_UNSIGNED_INT64_MASK = Int64(0xffff_ffff) - -inline fun Double.toInt64RawBits(): Int64 = Platform.toInt64RawBits(this) -inline fun Double.toLongRawBits(): Long = Platform.toInt64RawBits(this).toLong() -inline fun Double.toInt64(): Int64 = Platform.toInt64(this) -inline fun Long.toInt64(): Int64 = Platform.longToInt64(this) -inline fun Int.toInt64(): Int64 = Platform.toInt64(this) +inline fun Double.toInt64RawBits(): Long = toRawBits() +inline fun Double.toLongRawBits(): Long = toRawBits() +inline fun Double.toInt64(): Long = Platform.toInt64(this) +inline fun Long.toInt64(): Long = this +inline fun Int.toInt64(): Long = toLong() /** * Convert the integer into an unsigned 64-bit integer, so `-1` becomes `4294967295` _(aka `0xffffffff`)_. */ -inline fun Int.toUnsignedInt64(): Int64 = Platform.toInt64(this) and INT_TO_UNSIGNED_INT64_MASK +inline fun Int.toUnsignedInt64(): Long = toLong() and INT_TO_UNSIGNED_INT64_MASK inline fun AtomicMap(): AtomicMap = Platform.newAtomicMap() inline fun AtomicBool(initialValue: Boolean = false): AtomicBool = Platform.newAtomicBool(initialValue) inline fun AtomicInt(initialValue: Int = 0): AtomicInt = Platform.newAtomicInt(initialValue) -inline fun AtomicInt64(initialValue: Int64): AtomicInt64 = Platform.newAtomicInt64(initialValue) -inline fun AtomicInt64(initialValue: Long = 0): AtomicInt64 = Platform.newAtomicInt64(initialValue.toInt64()) +inline fun AtomicInt64(initialValue: Long = 0): AtomicInt64 = Platform.newAtomicInt64(initialValue) inline fun AtomicRef(referee: T?): AtomicRef = Platform.newAtomicRef(referee) inline fun AtomicNonNullRef(referee: T): AtomicNonNullRef = Platform.newAtomicNonNullRef(referee) inline fun WeakRef(referee: T): WeakRef = Platform.newWeakRef(referee) diff --git a/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/Platform.kt b/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/Platform.kt index fea1ad201..4615f905a 100644 --- a/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/Platform.kt +++ b/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/Platform.kt @@ -30,13 +30,13 @@ expect class Platform { * The maximum value of a 64-bit integer. * @return The maximum value of a 64-bit integer. */ - val INT64_MAX_VALUE: Int64 + val INT64_MAX_VALUE: Long /** * The minimum value of a 64-bit integer. * @return The minimum value of a 64-bit integer. */ - val INT64_MIN_VALUE: Int64 + val INT64_MIN_VALUE: Long /** * The minimum integer that can safely stored in a double. @@ -76,9 +76,9 @@ expect class Platform { val intKlass: KClass /** - * The KClass for [Int64]. + * The KClass for [Long]. */ - val int64Klass: KClass + val int64Klass: KClass /** * The KClass for [Double]. @@ -241,7 +241,7 @@ expect class Platform { * @param startValue the initial value. * @return the atomic integer. */ - fun newAtomicInt64(startValue: Int64): AtomicInt64 + fun newAtomicInt64(startValue: Long): AtomicInt64 /** * Creates a new byte-array of the given size. @@ -303,7 +303,7 @@ expect class Platform { /** * Create a 32-bit integer from the given value. - * @param value A value being either [Number], [Int64] or [String] that contains a decimal number. + * @param value A value being either [Number] or [String] that contains a decimal number. * @return The value as 32-bit integer. * @throws IllegalArgumentException If the given value fails to be converted into a 32-bit integer. */ @@ -315,11 +315,11 @@ expect class Platform { * @return The value as 64-bit integer. * @throws IllegalArgumentException If the given value fails to be converted into a 64-bit integer. */ - fun toInt64(value: Any): Int64 + fun toInt64(value: Any): Long /** * Create a 64-bit floating point number from the given value. - * @param value A value being either [Number], [Int64] or [String]. + * @param value A value being either [Number] or [String]. * @return The value as 64-bit floating point number. * @throws IllegalArgumentException If the given value fails to be converted into a 64-bit floating point number. */ @@ -332,7 +332,7 @@ expect class Platform { * @param i The 64-bit integer. * @return The integer converted into a double. */ - fun toDoubleRawBits(i: Int64): Double + fun toDoubleRawBits(i: Long): Double /** * Cast the given 64-bit floating point number into a 64-bit integer using only raw bits. That means, the 64-bits of the @@ -340,28 +340,28 @@ expect class Platform { * @param d The 64-bit double in [IEEE-754](https://en.wikipedia.org/wiki/IEEE_754) format. * @return The integer converted into a double. */ - fun toInt64RawBits(d: Double): Int64 + fun toInt64RawBits(d: Double): Long /** * Widen a 32-bit integer into a platform specific 64-bit integer. * @param value the 32-bit integer. * @return the platform specific 64-bit representation. */ - fun intToInt64(value: Int): Int64 + fun intToInt64(value: Int): Long /** * Converts an internal 64-bit integer into a platform specific. * @param value The internal 64-bit. * @return The platform specific 64-bit. */ - fun longToInt64(value: Long): Int64 + fun longToInt64(value: Long): Long /** * Converts a platform specific 64-bit integer into an internal one to be used for example with the [PlatformDataViewApi]. * @param value The platform specific 64-bit integer. * @return The internal 64-bit integer. */ - fun int64ToLong(value: Int64): Long + fun int64ToLong(value: Long): Long /** * Tests if the given object is a scalar, so _null_, _undefined_, any [Number], [String] or [Boolean]. @@ -371,16 +371,16 @@ expect class Platform { fun isScalar(o: Any?): Boolean /** - * Tests if the given object is a [Number] or [Int64]. + * Tests if the given object is a [Number]. * @param o The object to test. - * @return _true_ if the object is a [Number] or [Int64]; _false_ otherwise. + * @return _true_ if the object is a [Number]; _false_ otherwise. */ fun isNumber(o: Any?): Boolean /** - * Tests if the given object is a [Byte], [Short], [Int] or [Int64]. + * Tests if the given object is a [Byte], [Short], [Int] or [Long]. * @param o The object to test. - * @return _true_ if the object is a [Byte], [Short], [Int] or [Int64]; _false_ otherwise. + * @return _true_ if the object is a [Byte], [Short], [Int] or [Long]; _false_ otherwise. */ fun isInteger(o: Any?): Boolean @@ -440,7 +440,7 @@ expect class Platform { * - [Boolean] * - [Short] * - [Int] - * - [Int64] + * - [Long] * - [Float] * - [Double] * - [String] @@ -495,7 +495,7 @@ expect class Platform { /** * Convert the given platform native objects recursively into multi-platform objects. So all maps are corrected to [PlatformMap], - * all strings starting with `data:bigint,` or Java `Long`'s are converted into [Int64]'s, lists are corrected to [PlatformList], + * all strings starting with `data:bigint,` are converted into [Long]'s, lists are corrected to [PlatformList], * and so on. This can be used after a JSON was parsed from an arbitrary platform tool into some platform specific standard * objects or when exchanging data with a platform specific library that does not like the multi-platform objects. * @param obj The platform native objects to convert recursively. @@ -518,19 +518,19 @@ expect class Platform { * Returns the current epoch milliseconds. * @return The current epoch milliseconds. */ - fun currentMillis(): Int64 + fun currentMillis(): Long /** * Returns the current epoch microseconds. * @return current epoch microseconds. */ - fun currentMicros(): Int64 + fun currentMicros(): Long /** * Returns the current epoch nanoseconds. * @return current epoch nanoseconds. */ - fun currentNanos(): Int64 + fun currentNanos(): Long /** * Generates a new random number between 0 and 1 (therefore with 53-bit random bits). diff --git a/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/PlatformDataViewApi.kt b/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/PlatformDataViewApi.kt index aca72e063..cc88012e8 100644 --- a/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/PlatformDataViewApi.kt +++ b/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/PlatformDataViewApi.kt @@ -139,7 +139,7 @@ expect class PlatformDataViewApi { * @return the read value. * @since 3.0.0 */ - fun dataview_get_int64(view: PlatformDataView, pos: Int, littleEndian: Boolean = false): Int64 + fun dataview_get_int64(view: PlatformDataView, pos: Int, littleEndian: Boolean = false): Long /** * Write a 64-bit integer into the view. @@ -149,7 +149,7 @@ expect class PlatformDataViewApi { * @param littleEndian _true_ if little-endian encoding should be used. * @since 3.0.0 */ - fun dataview_set_int64(view: PlatformDataView, pos: Int, value: Int64, littleEndian: Boolean = false) + fun dataview_set_int64(view: PlatformDataView, pos: Int, value: Long, littleEndian: Boolean = false) } } diff --git a/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/PlatformLock.kt b/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/PlatformLock.kt index 8c140b4c8..09db49470 100644 --- a/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/PlatformLock.kt +++ b/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/PlatformLock.kt @@ -35,10 +35,10 @@ interface PlatformLock : AutoCloseable { * locking will fail. * @return _true_, if the lock was acquired; _false_ if locking failed due to timeout. */ - fun tryAcquire(waitMillis: Int64? = null): Boolean + fun tryAcquire(waitMillis: Long? = null): Boolean /** * Release the lock. */ override fun close() -} \ No newline at end of file +} diff --git a/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/PlatformUtil.kt b/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/PlatformUtil.kt index 74b87197d..e7f59b288 100644 --- a/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/PlatformUtil.kt +++ b/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/PlatformUtil.kt @@ -48,56 +48,56 @@ class PlatformUtil { */ @JsStatic @JvmField - val FLOAT_MAX: Double = Platform.toDoubleRawBits(Int64(0x47efffffe0000000L)) + val FLOAT_MAX: Double = Double.fromBits(0x47efffffe0000000L) /** * The minimal 32-bit floating point number that can be encoded without losing precision. */ @JsStatic @JvmField - val FLOAT_MIN: Double = Platform.toDoubleRawBits(Int64(0x36a0000000000000L)) + val FLOAT_MIN: Double = Double.fromBits(0x36a0000000000000L) /** * A single milliseconds. */ @JsStatic @JvmField - val MILLISECOND = Int64(1) + val MILLISECOND = 1L /** * A second in milliseconds. */ @JsStatic @JvmField - val SECOND = Int64(1000) + val SECOND = 1000L /** * A minute in milliseconds. */ @JsStatic @JvmField - val MINUTE = Int64(60 * 1000) + val MINUTE = 60 * 1000L /** * An hour in milliseconds. */ @JsStatic @JvmField - val HOUR = Int64(60 * 60 * 1000) + val HOUR = 60 * 60 * 1000L /** * A day in milliseconds. */ @JsStatic @JvmField - val DAY = Int64(24 * 60 * 60 * 1000) + val DAY = 24 * 60 * 60 * 1000L /** * A multiplier to convert milliseconds to microseconds or a divider, to turn microseconds into millis. */ @JsStatic @JvmField - val MILLIS_TO_MICROS = Int64(1000) + val MILLIS_TO_MICROS = 1000L /** * The default size of a view. This is used at various placed. @@ -191,4 +191,4 @@ class PlatformUtil { } } } -} \ No newline at end of file +} diff --git a/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/Proxy.kt b/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/Proxy.kt index 751248a71..d11aeaedb 100644 --- a/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/Proxy.kt +++ b/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/Proxy.kt @@ -73,16 +73,12 @@ abstract class Proxy : PlatformObject { if (Platform.isAssignable(klass, JsEnum::class)) { return JsEnum.get(raw, klass as KClass) as T } - if (klass == Int64::class) { - val value = if (klass == Int64::class) when (raw) { - is Short -> Int64(raw.toInt()) - is Int -> Int64(raw) - is Long -> Int64(raw) - is Float -> Int64(raw.toDouble()) - is Double -> Int64(raw) + if (klass == Long::class) { + val value = when (raw) { + is Number -> raw.toLong() else -> raw - } else raw - if (value is Int64) return value as T + } + if (value is Long) return value as T } return if (init != null) init.call() else alternative } @@ -265,7 +261,6 @@ abstract class Proxy : PlatformObject { } if (current is PlatformMap) return Platform.proxy(current, AnyObject::class) if (current is PlatformList) return Platform.proxy(current, AnyList::class) - if (current is Int64) return current.toLong() return current } @@ -643,4 +638,4 @@ abstract class Proxy : PlatformObject { if (isRemove) return UNDEFINED throw illegalArg("Invalid key in path: '$key' at position $pathLast") } -} \ No newline at end of file +} diff --git a/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/Timestamp.kt b/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/Timestamp.kt index cf8d83f44..bb8c5b645 100644 --- a/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/Timestamp.kt +++ b/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/Timestamp.kt @@ -26,7 +26,7 @@ import kotlin.time.Instant */ @JsExport class Timestamp( - val ts: Int64, + val ts: Long, val year: Int, val month: Int, val day: Int, @@ -48,7 +48,7 @@ class Timestamp( val instant = Clock.System.now() val ldt = instant.toLocalDateTime(TimeZone.UTC) return Timestamp( - Int64(instant.toEpochMilliseconds()), + instant.toEpochMilliseconds(), ldt.year, ldt.month.number, ldt.day, @@ -68,8 +68,8 @@ class Timestamp( */ @JvmStatic @JsStatic - fun fromMillis(ts: Int64) : Timestamp { - val instant = Instant.fromEpochMilliseconds(ts.toLong()) + fun fromMillis(ts: Long) : Timestamp { + val instant = Instant.fromEpochMilliseconds(ts) val ldt = instant.toLocalDateTime(TimeZone.UTC) return Timestamp( ts, @@ -101,7 +101,7 @@ class Timestamp( val ldt = LocalDateTime(year, month, day, hour, minute, second, nanos) val instant = ldt.toInstant(TimeZone.UTC) return Timestamp( - Int64(instant.toEpochMilliseconds()), + instant.toEpochMilliseconds(), year, month, day, @@ -114,4 +114,4 @@ class Timestamp( ) } } -} \ No newline at end of file +} diff --git a/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/TupleNumber.kt b/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/TupleNumber.kt index 91e1ae627..54a0c6836 100644 --- a/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/TupleNumber.kt +++ b/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/TupleNumber.kt @@ -30,7 +30,7 @@ data class TupleNumber( * The database-number, uniquely identifies the storage where the tuple is stored. * @since 3.0 */ - @JvmField val databaseNumber: Int64, + @JvmField val databaseNumber: Long, /** * The catalog-number of the map in which the tuple is stored within the storage. @@ -48,7 +48,7 @@ data class TupleNumber( * The feature-number. * @since 3.0 */ - @JvmField val featureNumber: Int64, + @JvmField val featureNumber: Long, /** * The version _(transaction)_ of which the [naksha.model.Tuple] is part of. @@ -56,7 +56,7 @@ data class TupleNumber( * @since 3.0 * @see [Version.HEAD] */ - @JvmField val version: Int64, + @JvmField val version: Long, ) : Comparable { /** * The partition-number of the [naksha.model.Tuple], a value between `0` and `65536` _(exclusive)_. @@ -286,11 +286,11 @@ data class TupleNumber( @JvmOverloads fun copy( tn: TupleNumber, - version: Int64? = null, - featureNumber: Int64? = null, + version: Long? = null, + featureNumber: Long? = null, collectionNumber: Int? = null, mapNumber: Int? = null, - storageNumber: Int64? = null, + storageNumber: Long? = null, ) = TupleNumber( storageNumber ?: tn.databaseNumber, mapNumber ?: tn.catalogNumber, @@ -305,7 +305,7 @@ data class TupleNumber( * This happens for various reasons, for example when a [naksha.model.Tuple] is created in the client at runtime, and not yet persisted in any storage, therefore does not yet have a valid tuple-number. * @since 3.0 */ - val HEAD = TupleNumber(Int64(0), 0, 0, Int64(0), Version.HEAD.number) + val HEAD = TupleNumber(0, 0, 0, 0, Version.HEAD.number) /** * Restore a [TupleNumber] from a binary encoding. @@ -326,13 +326,13 @@ data class TupleNumber( fun fromB256(bytes: ByteArray) = fromByteArray(bytes, 0, TupleNumberVariant.B256) - fun fromB192(bytes: ByteArray, storageNumber: Int64) + fun fromB192(bytes: ByteArray, storageNumber: Long) = fromByteArray(bytes, 0, TupleNumberVariant.B192, storageNumber) - fun fromB160(bytes: ByteArray, storageNumber: Int64, mapNumber: Int) + fun fromB160(bytes: ByteArray, storageNumber: Long, mapNumber: Int) = fromByteArray(bytes, 0, TupleNumberVariant.B160, storageNumber, mapNumber) - fun fromB128(bytes: ByteArray, storageNumber: Int64, mapNumber: Int, collectionNumber: Int) + fun fromB128(bytes: ByteArray, storageNumber: Long, mapNumber: Int, collectionNumber: Int) = fromByteArray(bytes, 0, TupleNumberVariant.B128, storageNumber, mapNumber, collectionNumber) - fun fromB64(bytes: ByteArray, storageNumber: Int64, mapNumber: Int, collectionNumber: Int, featureNumber: Int64) + fun fromB64(bytes: ByteArray, storageNumber: Long, mapNumber: Int, collectionNumber: Int, featureNumber: Long) = fromByteArray(bytes, 0, TupleNumberVariant.B64, storageNumber, mapNumber, collectionNumber, featureNumber) /** @@ -352,10 +352,10 @@ data class TupleNumber( bytes: ByteArray, offset: Int = 0, variant: TupleNumberVariant = TupleNumberVariant.fromValue(bytes.size - offset), - storageNumber: Int64? = null, + storageNumber: Long? = null, mapNumber: Int? = null, collectionNumber: Int? = null, - featureNumber: Int64? = null + featureNumber: Long? = null ): TupleNumber = fromBinary(Binary(bytes, offset), variant, storageNumber, mapNumber, collectionNumber, featureNumber) /** @@ -374,10 +374,10 @@ data class TupleNumber( fun fromBinary( binary: Binary, variant: TupleNumberVariant, - storageNumber: Int64? = null, + storageNumber: Long? = null, mapNumber: Int? = null, collectionNumber: Int? = null, - featureNumber: Int64? = null + featureNumber: Long? = null ): TupleNumber { val storage_num = if (variant.encodeStorageNumber()) binary.readInt64() else storageNumber ?: throw illegalArg("Missing storage-number for given tuple-number variant $variant") @@ -460,10 +460,10 @@ data class TupleNumber( if (offset < 0 || (offset + ALL_PARTS) > parts.size) { throw illegalArg("Invalid tuple-number: $parts") } - val storageNumber = Int64(parts[offset + STORAGE_NUMBER].toLong(10)) + val storageNumber = parts[offset + STORAGE_NUMBER].toLong(10) val mapNumber = parts[offset + MAP_NUMBER].toInt(10) val colNumber = parts[offset + COLLECTION_NUMBER].toInt(10) - val featureNumber = Int64(parts[offset + FEATURE_NUMBER].toLong(10)) + val featureNumber = parts[offset + FEATURE_NUMBER].toLong(10) val version = Version.fromString(parts[offset + VERSION]).number return TupleNumber(storageNumber, mapNumber, colNumber, featureNumber, version) } diff --git a/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/Version.kt b/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/Version.kt index 965d4d69f..dfd9e21af 100644 --- a/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/Version.kt +++ b/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/Version.kt @@ -52,22 +52,13 @@ import kotlin.jvm.JvmStatic * @since 3.0 */ @JsExport -open class Version(@JvmField val number: Int64) : Comparable { +open class Version(@JvmField val number: Long) : Comparable { init { - if ((number and Int64(MAX_SAFE_INTEGER)) != number) { + if ((number and MAX_SAFE_INTEGER) != number) { throw illegalArg("$number is not a valid version") } } - /** - * Convert a [Long] into a [Int64] version. - * @param value the transaction number. - * @since 3.0 - */ - @Suppress("NON_EXPORTABLE_TYPE") - @JsName("fromLong") - constructor(value: Long) : this(Int64(value)) - /** * Convert a stringified version. * @param value the stringified version as decimal number. @@ -75,7 +66,7 @@ open class Version(@JvmField val number: Int64) : Comparable { * @throws NumberFormatException if the given string is no valid version. */ @JsName("fromString") - constructor(value: String) : this(Int64(value.toLong())) + constructor(value: String) : this(value.toLong()) companion object VersionCompanion { @@ -91,10 +82,10 @@ open class Version(@JvmField val number: Int64) : Comparable { private const val YEAR_MIN = 16 /** Mask for the 30-bit sequence field. */ - private val SEQ_30_MASK = Int64(0x3FFF_FFFF) + private const val SEQ_30_MASK = 0x3FFF_FFFFL /** Mask for the 41-bit manual-version seq field (upper 21 bits of the 64-bit value must be 0). */ - private val MANUAL_SEQ_MASK = Int64(0x1FF_FFFF_FFFF) // 41 bits; 2,199,023,255,551 + private const val MANUAL_SEQ_MASK = 0x1FF_FFFF_FFFFL // 41 bits; 2,199,023,255,551 /** * Create a version from a double (JavaScript number). @@ -103,7 +94,7 @@ open class Version(@JvmField val number: Int64) : Comparable { */ @JsStatic @JvmStatic - fun fromDouble(v: Double): Version = Version(Int64(v)) + fun fromDouble(v: Double): Version = Version(v.toLong()) /** * Creates a version from its string representation. @@ -120,7 +111,7 @@ open class Version(@JvmField val number: Int64) : Comparable { @JvmStatic fun fromString(s: String): Version { try { - return Version(Int64(s.toLong())) + return Version(s.toLong()) } catch (_: Exception) { throw illegalArg("Invalid version string: $s") } @@ -139,18 +130,18 @@ open class Version(@JvmField val number: Int64) : Comparable { */ @JvmStatic @JsStatic - fun auto(year: Int, month: Int, day: Int, seq: Int64, action: Action): Version { + fun auto(year: Int, month: Int, day: Int, seq: Long, action: Action): Version { if (year !in YEAR_MIN..YEAR_MAX) throw illegalArg("year must be in $YEAR_MIN..$YEAR_MAX, got $year") if (month !in 1..12) throw illegalArg("month must be in 1..12, got $month") if (day !in 1..31) throw illegalArg("day must be in 1..31, got $day") - if (!((seq >= Int64(0) && seq <= SEQ_30_MASK))) { - throw illegalArg("seq must be in 0..${SEQ_30_MASK.toLong()} (30-bit), got $seq") + if (seq !in 0..SEQ_30_MASK) { + throw illegalArg("seq must be in 0..$SEQ_30_MASK (30-bit), got $seq") } - val txn = (Int64(year) shl 41) or - (Int64(month) shl 37) or - (Int64(day) shl 32) or + val txn = (year.toLong() shl 41) or + (month.toLong() shl 37) or + (day.toLong() shl 32) or (seq shl 2) or - Int64(action.intValue) + action.intValue.toLong() return Version(txn) } @@ -166,11 +157,11 @@ open class Version(@JvmField val number: Int64) : Comparable { */ @JvmStatic @JsStatic - fun manual(seq: Int64, action: Action): Version { - if (!(seq >= Int64(0) && seq <= MANUAL_SEQ_MASK)) { - throw illegalArg("seq for a manual version must be in 0..${MANUAL_SEQ_MASK.toLong()} (41-bit), got $seq") + fun manual(seq: Long, action: Action): Version { + if (seq !in 0..MANUAL_SEQ_MASK) { + throw illegalArg("seq for a manual version must be in 0..$MANUAL_SEQ_MASK (41-bit), got $seq") } - return Version((seq shl 2) or Int64(action.intValue)) + return Version((seq shl 2) or action.intValue.toLong()) } /** @@ -182,12 +173,12 @@ open class Version(@JvmField val number: Int64) : Comparable { */ @JvmStatic @JsStatic - fun now(seq: Int64, action: Action): Version { + fun now(seq: Long, action: Action): Version { val now = Timestamp.now() return auto(now.year, now.month, now.day, seq, action) } - private val seq = AtomicInt64(Int64(0)) + private val seq = AtomicInt64() /** * Creates a new virtual version with the given action. Guarantees a unique version number like storages will do. @@ -199,7 +190,7 @@ open class Version(@JvmField val number: Int64) : Comparable { */ @JvmStatic @JsStatic - fun virtualVersion(action: Action): Version = now(seq.addAndGet(Int64(1)), action) + fun virtualVersion(action: Action): Version = now(seq.addAndGet(1), action) /** * Turns the given version into a real version, so setting the lower two bit to two, and ensure that the value is a valid version number. @@ -211,8 +202,8 @@ open class Version(@JvmField val number: Int64) : Comparable { */ @JvmStatic @JsStatic - fun asVersion(version: Int64): Int64 { - val v = version or Int64(3) + fun asVersion(version: Long): Long { + val v = version or 3L if (v > HEAD.number) return HEAD.number if (v < 0) throw illegalArg("Versions must not be negative") return v @@ -236,7 +227,7 @@ open class Version(@JvmField val number: Int64) : Comparable { */ @JvmField @JsStatic - val MIN_AUTO = auto(16, 1, 1, Int64(0), CREATE) + val MIN_AUTO = auto(16, 1, 1, 0, CREATE) // 0n + (0n << 2n) + (1n << 32n) + (1n << (32n+5n)) + (16n << (32n+5n+4n)) = 35326106009600n // bitwise: 0x0000_2021_0000_0000 @@ -246,7 +237,7 @@ open class Version(@JvmField val number: Int64) : Comparable { */ @JvmField @JsStatic - val MAX_AUTO = auto(4095, 12, 31, Int64(1_073_741_823), VERSION) + val MAX_AUTO = auto(4095, 12, 31, 1_073_741_823, VERSION) // 3n + (1073741823n << 2n) + (31n << 32n) + (12n << (32n+5n)) + (4095n << (32n+5n+4n)) = 9006786937880575n // bitwise: 0x001f_ff9f_ffff_ffff @@ -256,7 +247,7 @@ open class Version(@JvmField val number: Int64) : Comparable { */ @JvmField @JsStatic - val MIN_MANUAL = manual(Int64(1), CREATE) + val MIN_MANUAL = manual(1, CREATE) /** * The maximum valid manual version (seq=2,199,023,255,551, action=VERSION). @@ -288,7 +279,7 @@ open class Version(@JvmField val number: Int64) : Comparable { */ @JvmField @JsStatic - val SEQ_MIN: Int64 = Int64(0) + val SEQ_MIN: Long = 0 /** * The maximum value of the 30-bit sequence field (`0x3FFF_FFFF` = 1073741823). @@ -297,7 +288,7 @@ open class Version(@JvmField val number: Int64) : Comparable { */ @JvmField @JsStatic - val SEQ_MAX: Int64 = SEQ_30_MASK + val SEQ_MAX: Long = SEQ_30_MASK /** * The raw increment to add to [number] to advance the sequence counter by one while keeping the @@ -306,7 +297,7 @@ open class Version(@JvmField val number: Int64) : Comparable { */ @JvmField @JsStatic - val SEQ_INC: Int64 = Int64(1) shl 2 + val SEQ_INC: Long = 1L shl 2 /** * Tests if the given version encodes the [CREATE] action. @@ -316,7 +307,7 @@ open class Version(@JvmField val number: Int64) : Comparable { */ @JsStatic @JvmStatic - fun isCREATE(version: Int64): Boolean = (version.toLong() and 3L).toInt() == CREATE.intValue + fun isCREATE(version: Long): Boolean = (version and 3L).toInt() == CREATE.intValue /** * Tests if the given version encodes the [UPDATE] action. @@ -326,7 +317,7 @@ open class Version(@JvmField val number: Int64) : Comparable { */ @JsStatic @JvmStatic - fun isUPDATE(version: Int64): Boolean = (version.toLong() and 3L).toInt() == UPDATE.intValue + fun isUPDATE(version: Long): Boolean = (version and 3L).toInt() == UPDATE.intValue /** * Tests if the given version encodes the [DELETE] action. @@ -336,7 +327,7 @@ open class Version(@JvmField val number: Int64) : Comparable { */ @JsStatic @JvmStatic - fun isDELETE(version: Int64): Boolean = (version.toLong() and 3L).toInt() == DELETE.intValue + fun isDELETE(version: Long): Boolean = (version and 3L).toInt() == DELETE.intValue /** * Tests if the given version encodes the [VERSION] action. @@ -346,7 +337,7 @@ open class Version(@JvmField val number: Int64) : Comparable { */ @JsStatic @JvmStatic - fun isVERSION(version: Int64): Boolean = (version.toLong() and 3L).toInt() == VERSION.intValue + fun isVERSION(version: Long): Boolean = (version and 3L).toInt() == VERSION.intValue } private var _year = -1 @@ -386,7 +377,7 @@ open class Version(@JvmField val number: Int64) : Comparable { return _day } - private var _seq: Int64? = null + private var _seq: Long? = null /** * The 30-bit or 41-bit sequence number. @@ -395,7 +386,7 @@ open class Version(@JvmField val number: Int64) : Comparable { * - For manual versions this is the version-number shifted right by 2 _(1..2,199,023,255,551)_. * @since 3.0 */ - val seq: Int64 + val seq: Long get() { var s = _seq if (s == null) { @@ -431,14 +422,13 @@ open class Version(@JvmField val number: Int64) : Comparable { private var _string: String? = null override fun equals(other: Any?): Boolean { - if (other is Int64) return number eq other - if (other is Version) return number eq other.number + if (other is Long) return number == other + if (other is Version) return number == other.number return false } override fun compareTo(other: Version): Int { - val diff = number.minus(other.number) - return if (diff.eq(0)) 0 else if (diff < 0) -1 else 1 + return number.compareTo(other.number) } override fun hashCode(): Int = number.hashCode() @@ -454,7 +444,7 @@ open class Version(@JvmField val number: Int64) : Comparable { override fun toString(): String { var s = _string if (s == null) { - s = number.toLong().toString() + s = number.toString() _string = s } return s diff --git a/here-naksha-lib-base/src/commonTest/kotlin/naksha/base/Fnv1aTest.kt b/here-naksha-lib-base/src/commonTest/kotlin/naksha/base/Fnv1aTest.kt index 0691825b7..b12d38052 100644 --- a/here-naksha-lib-base/src/commonTest/kotlin/naksha/base/Fnv1aTest.kt +++ b/here-naksha-lib-base/src/commonTest/kotlin/naksha/base/Fnv1aTest.kt @@ -2,7 +2,6 @@ package naksha.base import kotlin.test.Test import kotlin.test.assertEquals -import kotlin.test.assertTrue class Fnv1aTest { @Test @@ -32,14 +31,13 @@ class Fnv1aTest { fun testFnv1a64() { // See: https://toolkitbay.com/tkb/tool/FNV-1 val testString = "test" - val expectedHash = Int64(0xf9e6e6ef197c2b25uL.toLong()) + val expectedHash = 0xf9e6e6ef197c2b25uL.toLong() var hash = Fnv1a64.start() var i = 0 while (i < testString.length) { val c = testString[i++] hash = Fnv1a64.int8(hash, (c.code and 0xff).toByte()) } - assertTrue(expectedHash eq hash) assertEquals(expectedHash, hash) } @@ -62,4 +60,4 @@ class Fnv1aTest { // expect assertEquals(Fnv1a32.start(), Fnv1a32.hashByteArray(null)) } -} \ No newline at end of file +} diff --git a/here-naksha-lib-base/src/commonTest/kotlin/naksha/base/Int64Test.kt b/here-naksha-lib-base/src/commonTest/kotlin/naksha/base/Int64Test.kt index 93ef19367..800ecd838 100644 --- a/here-naksha-lib-base/src/commonTest/kotlin/naksha/base/Int64Test.kt +++ b/here-naksha-lib-base/src/commonTest/kotlin/naksha/base/Int64Test.kt @@ -5,48 +5,39 @@ import kotlin.test.assertEquals class Int64Test { @Test - fun add() { - val a = Int64(10) - val b = Int64(5) - val c = a + b - assertEquals(15L, c.toLong()) - assertEquals(15, c.toInt()) + fun conversionUsesLong() { + assertEquals(Long.MAX_VALUE, Platform.toInt64(Long.MAX_VALUE)) + assertEquals(Long.MIN_VALUE, Platform.toInt64(Long.MIN_VALUE.toString())) + assertEquals(4_294_967_295L, (-1).toUnsignedInt64()) } @Test - fun sub() { - val a = Int64(10) - val b = Int64(5) - val c = a - b - assertEquals(5L, c.toLong()) - assertEquals(5, c.toInt()) - - } - - @Test - fun mul() { - val a = Int64(10) - val b = Int64(5) - val c = a * b - assertEquals(50L, c.toLong()) - assertEquals(50, c.toInt()) + fun atomicUsesLong() { + val atomic = AtomicInt64(Long.MAX_VALUE) + assertEquals(Long.MAX_VALUE, atomic.getAndAdd(1)) + assertEquals(Long.MIN_VALUE, atomic.get()) + assertEquals(Long.MIN_VALUE + 1, atomic.addAndGet(1)) + assertEquals(true, atomic.compareAndSet(Long.MIN_VALUE + 1, 42)) + assertEquals(42L, atomic.get()) } @Test - fun div() { - val a = Int64(10) - val b = Int64(5) - val c = a / b - assertEquals(2L, c.toLong()) - assertEquals(2, c.toInt()) + fun rawBitsRoundTrip() { + val bits = 0xfff8_0000_0000_0042uL.toLong() + val value = Platform.toDoubleRawBits(bits) + assertEquals(bits, Platform.toInt64RawBits(value)) + assertEquals(bits, value.toLongRawBits()) } @Test - fun mod() { - val a = Int64(10) - val b = Int64(5) - val c = a % b - assertEquals(0L, c.toLong()) - assertEquals(0, c.toInt()) + fun binaryPreservesBitsAndByteOrder() { + val value = 0x0123_4567_89ab_cdefL + val binary = Binary(16) + binary.setInt64(0, value) + binary.setInt64(8, value, littleEndian = true) + assertEquals(value, binary.getInt64(0)) + assertEquals(value, binary.getInt64(8, littleEndian = true)) + assertEquals(0x01, binary.byteArray[0].toInt()) + assertEquals(0xef, binary.byteArray[8].toInt() and 0xff) } -} \ No newline at end of file +} diff --git a/here-naksha-lib-base/src/commonTest/kotlin/naksha/base/PlatformTest.kt b/here-naksha-lib-base/src/commonTest/kotlin/naksha/base/PlatformTest.kt index dc5b850f3..96339fc21 100644 --- a/here-naksha-lib-base/src/commonTest/kotlin/naksha/base/PlatformTest.kt +++ b/here-naksha-lib-base/src/commonTest/kotlin/naksha/base/PlatformTest.kt @@ -28,11 +28,11 @@ class PlatformTest { assertEquals(14, xyz.getAs("someInt", Int::class)) assertTrue(xyz["bigInt"] is Number) val hexBigInt = xyz["hexBigInt"] - assertTrue(hexBigInt is Int64) - assertEquals(Int64(9007199254740991L), hexBigInt) + assertIs(hexBigInt) + assertEquals(9007199254740991L, hexBigInt) val decimalBigInt = xyz["decimalBigInt"] - assertTrue(decimalBigInt is Int64) - assertEquals(Int64(9007199254740991L), decimalBigInt) + assertIs(decimalBigInt) + assertEquals(9007199254740991L, decimalBigInt) val tags = xyz.getAs("tags", StringList::class) assertNotNull(tags) assertEquals(2, tags.size) @@ -69,4 +69,4 @@ class PlatformTest { assertEquals("\u00C5h no \u0066\u0069", Platform.normalize(str, NormalizerForm.NFKC)) assertEquals("\u0041\u030Ah no \u0066\u0069", Platform.normalize(str, NormalizerForm.NFKD)) } -} \ No newline at end of file +} diff --git a/here-naksha-lib-base/src/jsMain/kotlin/naksha/base/JsAtomicInt64.kt b/here-naksha-lib-base/src/jsMain/kotlin/naksha/base/JsAtomicInt64.kt index 8cc238ce8..5eeaca51a 100644 --- a/here-naksha-lib-base/src/jsMain/kotlin/naksha/base/JsAtomicInt64.kt +++ b/here-naksha-lib-base/src/jsMain/kotlin/naksha/base/JsAtomicInt64.kt @@ -4,14 +4,14 @@ package naksha.base * An atomic int 64 implementation for JavaScript. */ @JsExport -class JsAtomicInt64 internal constructor(private var _value: Int64): AtomicInt64 { - override fun get(): Int64 = _value +class JsAtomicInt64 internal constructor(private var _value: Long): AtomicInt64 { + override fun get(): Long = _value - override fun set(value: Int64) { + override fun set(value: Long) { _value = value } - override fun compareAndSet(expect: Int64, update: Int64): Boolean { + override fun compareAndSet(expect: Long, update: Long): Boolean { if (_value == expect) { _value = update return true @@ -19,14 +19,14 @@ class JsAtomicInt64 internal constructor(private var _value: Int64): AtomicInt64 return false } - override fun getAndAdd(value: Int64): Int64 { + override fun getAndAdd(value: Long): Long { val old = _value _value += value return old } - override fun addAndGet(value: Int64): Int64 { + override fun addAndGet(value: Long): Long { _value += value return _value } -} \ No newline at end of file +} diff --git a/here-naksha-lib-base/src/jsMain/kotlin/naksha/base/JsInt64.kt b/here-naksha-lib-base/src/jsMain/kotlin/naksha/base/JsInt64.kt index b8f01569e..43c2d6183 100644 --- a/here-naksha-lib-base/src/jsMain/kotlin/naksha/base/JsInt64.kt +++ b/here-naksha-lib-base/src/jsMain/kotlin/naksha/base/JsInt64.kt @@ -94,7 +94,7 @@ class JsInt64 internal constructor(): Int64 { override fun toDouble(): Double = js("Number(this.valueOf())").unsafeCast() - override fun toDoubleRawBits(): Double = Platform.toDoubleRawBits(this) + override fun toDoubleRawBits(): Double = Double.fromBits(toLong()) override fun hashCode(): Int { val u: dynamic = js("BigInt.asUintN(64, this.valueOf())") @@ -104,4 +104,4 @@ class JsInt64 internal constructor(): Int64 { return js("BigInt.asUintN(32,r)").unsafeCast() } // var u=BigInt.u64(t); return BigInt.s32((u >> BigInt(32)) ^ (u & BigInt.MASK_LO_32)); -} \ No newline at end of file +} diff --git a/here-naksha-lib-base/src/jsMain/kotlin/naksha/base/JsLock.kt b/here-naksha-lib-base/src/jsMain/kotlin/naksha/base/JsLock.kt index fc5c74346..33a10ff8a 100644 --- a/here-naksha-lib-base/src/jsMain/kotlin/naksha/base/JsLock.kt +++ b/here-naksha-lib-base/src/jsMain/kotlin/naksha/base/JsLock.kt @@ -4,7 +4,7 @@ package naksha.base class JsLock : PlatformLock { override fun acquire(): PlatformLock = this - override fun tryAcquire(waitMillis: Int64?): Boolean = true + override fun tryAcquire(waitMillis: Long?): Boolean = true override fun close() {} -} \ No newline at end of file +} diff --git a/here-naksha-lib-base/src/jsMain/kotlin/naksha/base/Platform.kt b/here-naksha-lib-base/src/jsMain/kotlin/naksha/base/Platform.kt index e09f3ece1..1af57feb2 100644 --- a/here-naksha-lib-base/src/jsMain/kotlin/naksha/base/Platform.kt +++ b/here-naksha-lib-base/src/jsMain/kotlin/naksha/base/Platform.kt @@ -97,6 +97,16 @@ actual class Platform { override fun deref(): Int = 0 } + // Fix that `if (longValue instanceof Number)` works. +// js(""" +//Object.defineProperty(Number, Symbol.hasInstance, { +// value(x) { +// return typeof x === "number" || +// typeof x === "bigint" || +// x instanceof Number; +// } +//}); +//""") copyPrototypeToPrototype(objectTemplate, js("{}").unsafeCast()) copyPrototypeToPrototype(listTemplate, js("[]").unsafeCast()) copyPrototypeToPrototype(mapTemplate, js("new Map()").unsafeCast()) @@ -104,26 +114,6 @@ actual class Platform { copyPrototypeToPrototype(symbolTemplate, js("Symbol()").unsafeCast()) copyPrototypeToPrototype(weakRefTemplate, js("new WeakRef(Object(0))").unsafeCast()) - copyPrototypeToPrototype(JsInt64(), js("BigInt(0)").unsafeCast()) - // Patch the Int64::class, so that it works as expected (it should only detect BigInt!) - val i64Class = Int64::class - js( - """ - var pt = Object.getPrototypeOf(i64Class); - var keys = Object.getOwnPropertyNames(pt); - var isInstanceOfName = null; - var i; - for (i in keys) { - var key = keys[i]; - if (key.startsWith("isInstance")) isInstanceOfName = key; - }; - // Note: Do not override pt[isInstanceOfName]! - // If we do this, then all isInstanceOf calls are overloaded, - // but we only want to overload the one of Int64::class! - i64Class[isInstanceOfName] = function(value) { - return value != null && typeof value.valueOf()==="bigint"; - };""" - ) return true } return false @@ -139,10 +129,10 @@ actual class Platform { actual val ITERATOR: Symbol = js("Symbol.iterator").unsafeCast() @JsStatic - actual val INT64_MAX_VALUE: Int64 = js("BigInt('9223372036854775807')").unsafeCast() + actual val INT64_MAX_VALUE: Long = Long.MAX_VALUE @JsStatic - actual val INT64_MIN_VALUE: Int64 = js("BigInt('-9223372036854775808')").unsafeCast() + actual val INT64_MIN_VALUE: Long = Long.MIN_VALUE @JsStatic actual val MAX_SAFE_INT: Double = 9007199254740991.0 @@ -188,7 +178,7 @@ actual class Platform { actual fun newAtomicInt(startValue: Int): AtomicInt = JsAtomicInt(startValue) @JsStatic - actual fun newAtomicInt64(startValue: Int64): AtomicInt64 = JsAtomicInt64(startValue) + actual fun newAtomicInt64(startValue: Long): AtomicInt64 = JsAtomicInt64(startValue) @JsStatic actual fun newList(vararg entries: Any?): PlatformList { @@ -235,46 +225,42 @@ actual class Platform { @JsStatic actual fun toInt(value: Any): Int = when (value) { is Long -> value.toInt() - is Int64 -> value.toInt() is Number -> value.toInt() is String -> value.toInt() else -> throw IllegalArgumentException("Failed to convert object to int") } @JsStatic - actual fun toInt64(value: Any): Int64 = when (value) { - is Long -> longToInt64(value) - is Int64 -> value - is Byte, Short, Int -> js("BigInt(value)").unsafeCast() - is Float, Double -> js("BigInt(Math.round(value))").unsafeCast() - is String -> js("BigInt(value)").unsafeCast() + actual fun toInt64(value: Any): Long = when (value) { + is Number -> value.toLong() + is String -> value.toLong() else -> throw IllegalArgumentException("Failed to convert object to int64") } @JsStatic actual fun toDouble(value: Any): Double = when (value) { is Long -> value.toDouble() - is Int64 -> value.toDouble() is Number -> value.toDouble() is String -> value.toDouble() else -> throw IllegalArgumentException("Failed to convert object to double") } @JsStatic - actual fun intToInt64(value: Int): Int64 = js("BigInt(value)").unsafeCast() + actual fun intToInt64(value: Int): Long = value.toLong() @JsStatic @Suppress("NON_EXPORTABLE_TYPE") - actual fun longToInt64(value: Long): Int64 { + actual fun longToInt64(value: Long): Long = value + + internal fun longToLegacyInt64(value: Long): Int64 { val view = convertView view.setInt32(0, (value ushr 32).toInt()) view.setInt32(4, value.toInt()) return view.getBigInt64(0).unsafeCast() } - @JsStatic @Suppress("NON_EXPORTABLE_TYPE") - actual fun int64ToLong(value: Int64): Long { + internal fun int64ToLong(value: Int64): Long { val view = convertView view.setBigInt64(0, value) val hi = view.getInt32(0).unsafeCast() @@ -285,16 +271,13 @@ actual class Platform { private val convertView: dynamic = js("new DataView(new ArrayBuffer(16))") @JsStatic - actual fun toInt64RawBits(d: Double): Int64 { - convertView.setFloat64(0, d) - return convertView.getBigInt64(0).unsafeCast() - } + actual fun toInt64RawBits(d: Double): Long = d.toRawBits() @JsStatic - actual fun toDoubleRawBits(i: Int64): Double { - convertView.setBigInt64(0, i) - return convertView.getFloat64(0).unsafeCast() - } + actual fun toDoubleRawBits(i: Long): Double = Double.fromBits(i) + + @JsStatic + actual fun int64ToLong(value: Long): Long = value @JsStatic actual fun isNumber(o: Any?): Boolean = @@ -415,11 +398,11 @@ if (typeof k==='function') instance=Object.create(k.prototype);""") actual val intKlass: KClass = Int::class /** - * The KClass for [Int64]. + * The KClass for [Long]. */ @Suppress("NON_EXPORTABLE_TYPE") @JsStatic - actual val int64Klass: KClass = Int64::class + actual val int64Klass: KClass = Long::class /** * The KClass for [Double]. @@ -665,21 +648,21 @@ return obj; * @return The current epoch milliseconds. */ @JsStatic - actual fun currentMillis(): Int64 = js("BigInt(Date.now())").unsafeCast() + actual fun currentMillis(): Long = js("Date.now()").unsafeCast().toLong() /** * Returns the current epoch microseconds. * @return current epoch microseconds. */ @JsStatic - actual fun currentMicros(): Int64 = js("BigInt(Date.now()*1000)").unsafeCast() + actual fun currentMicros(): Long = js("Date.now()*1000").unsafeCast().toLong() /** * Returns the current epoch nanoseconds. * @return current epoch nanoseconds. */ @JsStatic - actual fun currentNanos(): Int64 = js("BigInt(Date.now()*1000*1000)").unsafeCast() + actual fun currentNanos(): Long = js("Date.now()*1000*1000").unsafeCast().toLong() /** * Generates a new random number between 0 and 1 (therefore with 53-bit random bits). @@ -688,8 +671,8 @@ return obj; @JsStatic actual fun random(): Double = js("Math.random()").unsafeCast() - private val MANTISSA_MASK = Int64(0x000f_ffff_ffff_ffffL) - private val MANTISSA_LO_MASK = Int64(0x0000_0000_1fff_ffffL) + private const val MANTISSA_MASK = 0x000f_ffff_ffff_ffffL + private const val MANTISSA_LO_MASK = 0x0000_0000_1fff_ffffL /** * Tests if the given 64-bit floating point number can be converted into a 32-bit floating point number without losing information. @@ -713,8 +696,8 @@ return obj; if (exponent < -126 || exponent > 127) return false // We do not want to lose precision in mantissa either. // Either the lower 29-bit of mantissa are zero (only 23-bit used) or all bits are set. - val mantissa = view.getBigInt64(0).unsafeCast() and MANTISSA_MASK - return (mantissa and MANTISSA_LO_MASK) == I64_ZERO || mantissa == MANTISSA_MASK + val mantissa = value.toRawBits() and MANTISSA_MASK + return (mantissa and MANTISSA_LO_MASK) == 0L || mantissa == MANTISSA_MASK } private const val MIN_INT_VALUE_AS_DOUBLE = Int.MIN_VALUE.toDouble() diff --git a/here-naksha-lib-base/src/jsMain/kotlin/naksha/base/PlatformDataViewApi.kt b/here-naksha-lib-base/src/jsMain/kotlin/naksha/base/PlatformDataViewApi.kt index 26f432ac4..d17d2c589 100644 --- a/here-naksha-lib-base/src/jsMain/kotlin/naksha/base/PlatformDataViewApi.kt +++ b/here-naksha-lib-base/src/jsMain/kotlin/naksha/base/PlatformDataViewApi.kt @@ -96,17 +96,17 @@ actual class PlatformDataViewApi { view: PlatformDataView, pos: Int, littleEndian: Boolean - ): Int64 = view.asDynamic().getBigInt64(pos, littleEndian).unsafeCast() + ): Long = view.asDynamic().getBigInt64(pos, littleEndian).unsafeCast() @JsStatic actual fun dataview_set_int64( view: PlatformDataView, pos: Int, - value: Int64, + value: Long, littleEndian: Boolean ) { view.asDynamic().setBigInt64(pos, value, littleEndian) } } -} \ No newline at end of file +} diff --git a/here-naksha-lib-base/src/jvmMain/java/naksha/base/JvmParser.java b/here-naksha-lib-base/src/jvmMain/java/naksha/base/JvmParser.java index 4ec237181..21a8e2714 100644 --- a/here-naksha-lib-base/src/jvmMain/java/naksha/base/JvmParser.java +++ b/here-naksha-lib-base/src/jvmMain/java/naksha/base/JvmParser.java @@ -21,8 +21,8 @@ public class JvmParser extends JsonParser { @Override protected @NotNull Object newLong(long value) { if (value < Integer.MIN_VALUE || value > Integer.MAX_VALUE) { - return NumberUtil.boxInt64(value); + return value; } return NumberUtil.boxInt((int)value); } -} \ No newline at end of file +} diff --git a/here-naksha-lib-base/src/jvmMain/kotlin/naksha/base/CustomDeserializer.kt b/here-naksha-lib-base/src/jvmMain/kotlin/naksha/base/CustomDeserializer.kt index 1b8b2add0..4104ee9c1 100644 --- a/here-naksha-lib-base/src/jvmMain/kotlin/naksha/base/CustomDeserializer.kt +++ b/here-naksha-lib-base/src/jvmMain/kotlin/naksha/base/CustomDeserializer.kt @@ -4,7 +4,6 @@ import com.fasterxml.jackson.core.JsonParser import com.fasterxml.jackson.databind.DeserializationContext import com.fasterxml.jackson.databind.JsonDeserializer import com.fasterxml.jackson.databind.JsonNode -import naksha.base.Platform.PlatformCompanion.longToInt64 import kotlin.io.encoding.Base64 import kotlin.io.encoding.ExperimentalEncodingApi @@ -14,7 +13,7 @@ object CustomDeserializer : JsonDeserializer() { override fun deserialize(p: JsonParser, ctxt: DeserializationContext): Any? { val value = p.codec.readTree(p) if (value.isLong) { - return longToInt64(value.longValue()) + return value.longValue() } else if (value.isInt || value.isShort) { return value.intValue() @@ -30,10 +29,10 @@ object CustomDeserializer : JsonDeserializer() { val encoding = parts[0] val number = parts[1] when (encoding) { - "hex" -> return longToInt64(number.removePrefix("0x").toLong(16)) - "dec" -> return longToInt64(number.toLong()) - "oct" -> return longToInt64(number.removePrefix("0").toLong(8)) - "bin" -> return longToInt64(number.removePrefix("0b").toLong(2)) + "hex" -> return number.removePrefix("0x").toLong(16) + "dec" -> return number.toLong() + "oct" -> return number.removePrefix("0").toLong(8) + "bin" -> return number.removePrefix("0b").toLong(2) } } if (asText.startsWith("data:application/octet-stream;") && Platform.fromJsonOptions.get().parseDataUrl) { diff --git a/here-naksha-lib-base/src/jvmMain/kotlin/naksha/base/JvmAtomicInt64.kt b/here-naksha-lib-base/src/jvmMain/kotlin/naksha/base/JvmAtomicInt64.kt index 6c439264b..9943bee7e 100644 --- a/here-naksha-lib-base/src/jvmMain/kotlin/naksha/base/JvmAtomicInt64.kt +++ b/here-naksha-lib-base/src/jvmMain/kotlin/naksha/base/JvmAtomicInt64.kt @@ -4,22 +4,16 @@ import java.util.concurrent.atomic.AtomicLong class JvmAtomicInt64 internal constructor(initialValue: Long): AtomicInt64 { - internal constructor(value: Int64) : this(value.toLong()) - private val atomicLong: AtomicLong = AtomicLong(initialValue) - override fun get(): Int64 = - Int64(atomicLong.get()) + override fun get(): Long = atomicLong.get() - override fun set(value: Int64) = - atomicLong.set(value.toLong()) + override fun set(value: Long) = atomicLong.set(value) - override fun compareAndSet(expect: Int64, update: Int64): Boolean = - atomicLong.compareAndSet(expect.toLong(), update.toLong()) + override fun compareAndSet(expect: Long, update: Long): Boolean = + atomicLong.compareAndSet(expect, update) - override fun getAndAdd(value: Int64): Int64 = - Int64(atomicLong.getAndAdd(value.toLong())) + override fun getAndAdd(value: Long): Long = atomicLong.getAndAdd(value) - override fun addAndGet(value: Int64): Int64 = - Int64(atomicLong.addAndGet(value.toLong())) -} \ No newline at end of file + override fun addAndGet(value: Long): Long = atomicLong.addAndGet(value) +} diff --git a/here-naksha-lib-base/src/jvmMain/kotlin/naksha/base/JvmDataView.kt b/here-naksha-lib-base/src/jvmMain/kotlin/naksha/base/JvmDataView.kt index 39e953568..bcdbd00b9 100644 --- a/here-naksha-lib-base/src/jvmMain/kotlin/naksha/base/JvmDataView.kt +++ b/here-naksha-lib-base/src/jvmMain/kotlin/naksha/base/JvmDataView.kt @@ -1,6 +1,5 @@ package naksha.base -import naksha.base.Platform.PlatformCompanion.longToInt64 import java.nio.ByteOrder import kotlin.reflect.KClass import kotlin.reflect.full.primaryConstructor @@ -126,13 +125,12 @@ open class JvmDataView(byteArray: ByteArray, offset: Int = 0, length: Int = byte Platform.unsafe.putInt(buffer, offset(pos, 4), ordered(value, littleEndian)) } - fun getInt64(pos: Int, littleEndian: Boolean): Int64 { + fun getInt64(pos: Int, littleEndian: Boolean): Long { val value = Platform.unsafe.getLong(buffer, offset(pos, 8)) - return longToInt64(ordered(value, littleEndian)) + return ordered(value, littleEndian) } - fun setInt64(pos: Int, value: Int64, littleEndian: Boolean) { - check(value is JvmInt64) - Platform.unsafe.putLong(buffer, offset(pos, 8), ordered(value.toLong(), littleEndian)) + fun setInt64(pos: Int, value: Long, littleEndian: Boolean) { + Platform.unsafe.putLong(buffer, offset(pos, 8), ordered(value, littleEndian)) } -} \ No newline at end of file +} diff --git a/here-naksha-lib-base/src/jvmMain/kotlin/naksha/base/JvmInt64.kt b/here-naksha-lib-base/src/jvmMain/kotlin/naksha/base/JvmInt64.kt index 24a9e5b48..573b3d7b7 100644 --- a/here-naksha-lib-base/src/jvmMain/kotlin/naksha/base/JvmInt64.kt +++ b/here-naksha-lib-base/src/jvmMain/kotlin/naksha/base/JvmInt64.kt @@ -1,7 +1,5 @@ package naksha.base -import naksha.base.Platform.PlatformCompanion.longToInt64 - /** * The JVM Int64 implementation. If an instance is needed use [Platform.longToInt64]. */ @@ -12,22 +10,22 @@ class JvmInt64 internal constructor(internal val value: Long) : Number(), Int64 private inline fun l(i: Int): Long = i.toLong() override fun unaryPlus(): Int64 = this - override fun unaryMinus(): Int64 = longToInt64(-value) - override fun inc(): Int64 = longToInt64(value + 1) - override fun dec(): Int64 = longToInt64(value - 1) - override fun plus(other: Any): Int64 = longToInt64(value + l(other)) - override fun minus(other: Any): Int64 = longToInt64(value - l(other)) - override fun times(other: Any): Int64 = longToInt64(value * l(other)) - override fun div(other: Any): Int64 = longToInt64(value / l(other)) - override fun rem(other: Any): Int64 = longToInt64(value % l(other)) + override fun unaryMinus(): Int64 = JvmInt64(-value) + override fun inc(): Int64 = JvmInt64(value + 1) + override fun dec(): Int64 = JvmInt64(value - 1) + override fun plus(other: Any): Int64 = JvmInt64(value + l(other)) + override fun minus(other: Any): Int64 = JvmInt64(value - l(other)) + override fun times(other: Any): Int64 = JvmInt64(value * l(other)) + override fun div(other: Any): Int64 = JvmInt64(value / l(other)) + override fun rem(other: Any): Int64 = JvmInt64(value % l(other)) override fun compareTo(other: Any?): Int = value.compareTo(l(other)) - override fun shr(bits: Int): Int64 = longToInt64(value shr bits) - override fun ushr(bits: Int): Int64 = longToInt64(value ushr bits) - override fun shl(bits: Int): Int64 = longToInt64(value shl bits) - override fun and(other: Int64): Int64 = longToInt64(value and l(other)) - override fun or(other: Int64): Int64 = longToInt64(value or l(other)) - override fun xor(other: Int64): Int64 = longToInt64(value xor l(other)) - override fun inv(): Int64 = longToInt64(value.inv()) + override fun shr(bits: Int): Int64 = JvmInt64(value shr bits) + override fun ushr(bits: Int): Int64 = JvmInt64(value ushr bits) + override fun shl(bits: Int): Int64 = JvmInt64(value shl bits) + override fun and(other: Int64): Int64 = JvmInt64(value and l(other)) + override fun or(other: Int64): Int64 = JvmInt64(value or l(other)) + override fun xor(other: Int64): Int64 = JvmInt64(value xor l(other)) + override fun inv(): Int64 = JvmInt64(value.inv()) override fun toByte(): Byte = value.toByte() override fun toShort(): Short = value.toShort() override fun toInt(): Int = value.toInt() @@ -42,4 +40,4 @@ class JvmInt64 internal constructor(internal val value: Long) : Number(), Int64 } override fun hashCode(): Int = (value ushr 32).toInt() xor value.toInt() override fun toString(): String = value.toString() -} \ No newline at end of file +} diff --git a/here-naksha-lib-base/src/jvmMain/kotlin/naksha/base/JvmLock.kt b/here-naksha-lib-base/src/jvmMain/kotlin/naksha/base/JvmLock.kt index 294e20ef6..5397ff919 100644 --- a/here-naksha-lib-base/src/jvmMain/kotlin/naksha/base/JvmLock.kt +++ b/here-naksha-lib-base/src/jvmMain/kotlin/naksha/base/JvmLock.kt @@ -1,12 +1,11 @@ package naksha.base -import naksha.base.Platform.PlatformCompanion.longToInt64 import java.util.concurrent.TimeUnit.MILLISECONDS import java.util.concurrent.locks.ReentrantLock class JvmLock : ReentrantLock(), PlatformLock { companion object { - private val MIN_WAIT = longToInt64(1) + private const val MIN_WAIT = 1L } override fun acquire(): PlatformLock { @@ -14,10 +13,10 @@ class JvmLock : ReentrantLock(), PlatformLock { return this } - override fun tryAcquire(waitMillis: Int64?): Boolean - = if (waitMillis == null || waitMillis.toLong() < 1L ) super.tryLock() else super.tryLock(waitMillis.toLong(), MILLISECONDS) + override fun tryAcquire(waitMillis: Long?): Boolean + = if (waitMillis == null || waitMillis < MIN_WAIT) super.tryLock() else super.tryLock(waitMillis, MILLISECONDS) override fun close() { super.unlock() } -} \ No newline at end of file +} diff --git a/here-naksha-lib-base/src/jvmMain/kotlin/naksha/base/Platform.kt b/here-naksha-lib-base/src/jvmMain/kotlin/naksha/base/Platform.kt index 8bb925f7d..6ee6fa058 100644 --- a/here-naksha-lib-base/src/jvmMain/kotlin/naksha/base/Platform.kt +++ b/here-naksha-lib-base/src/jvmMain/kotlin/naksha/base/Platform.kt @@ -155,14 +155,14 @@ actual class Platform { * @return The maximum value of a 64-bit integer. */ @JvmField - actual val INT64_MAX_VALUE: Int64 = JvmInt64(Long.MAX_VALUE) + actual val INT64_MAX_VALUE: Long = Long.MAX_VALUE /** * The minimum value of a 64-bit integer. * @return The minimum value of a 64-bit integer. */ @JvmField - actual val INT64_MIN_VALUE: Int64 = JvmInt64(Long.MIN_VALUE) + actual val INT64_MIN_VALUE: Long = Long.MIN_VALUE /** * The minimum integer that can safely stored in a double. @@ -328,10 +328,7 @@ actual class Platform { actual fun newAtomicInt(startValue: Int): AtomicInt = JvmAtomicInt(startValue) @JvmStatic - actual fun newAtomicInt64(startValue: Int64): AtomicInt64 = JvmAtomicInt64(startValue) - - @JvmStatic - fun newAtomicInt64(startValue: Long): AtomicInt64 = JvmAtomicInt64(startValue) + actual fun newAtomicInt64(startValue: Long): AtomicInt64 = JvmAtomicInt64(startValue) @JvmStatic actual fun newList(vararg entries: Any?): PlatformList = JvmList(*entries) @@ -372,9 +369,9 @@ actual class Platform { } @JvmStatic - actual fun toInt64(value: Any): Int64 = when (value) { - is Number -> longToInt64(value.toLong()) - is String -> longToInt64(java.lang.Long.parseLong(value)) + actual fun toInt64(value: Any): Long = when (value) { + is Number -> value.toLong() + is String -> java.lang.Long.parseLong(value) else -> throw IllegalArgumentException("Failed to convert object to 64-bit integer") } @@ -386,7 +383,7 @@ actual class Platform { } @JvmStatic - actual fun toDoubleRawBits(i: Int64): Double = java.lang.Double.longBitsToDouble(i.toLong()) + actual fun toDoubleRawBits(i: Long): Double = java.lang.Double.longBitsToDouble(i) @JvmStatic fun toLong(value: Any): Long = when (value) { @@ -396,32 +393,16 @@ actual class Platform { } @JvmStatic - actual fun toInt64RawBits(d: Double): Int64 = longToInt64(java.lang.Double.doubleToRawLongBits(d)) + actual fun toInt64RawBits(d: Double): Long = java.lang.Double.doubleToRawLongBits(d) @JvmStatic - actual fun intToInt64(value: Int): Int64 { - if (value >= -1024 && value < 1024) return int64Cache[(value shl 21) ushr 21] - return longToInt64(value.toLong()) - } + actual fun intToInt64(value: Int): Long = value.toLong() @JvmStatic - actual fun longToInt64(value: Long): Int64 { - if (value >= -1024 && value < 1024) return int64Cache[(value.toInt() shl 21) ushr 21] - if (value == INT64_MAX_VALUE.toLong()) return INT64_MAX_VALUE - if (value == INT64_MIN_VALUE.toLong()) return INT64_MIN_VALUE - // This is a very simple hash-based cache, it is helpful for example for currentMillis. - val cache = this.int64ValueCache - val cacheMask = cache.size - 1 - val i = (value.toInt() xor (value ushr 32).toInt()) and cacheMask - var instance = cache[i] - if (instance != null && instance.value == value) return instance - instance = JvmInt64(value) - cache[i] = instance - return instance - } + actual fun longToInt64(value: Long): Long = value @JvmStatic - actual fun int64ToLong(value: Int64): Long = value.toLong() + actual fun int64ToLong(value: Long): Long = value @JvmStatic actual fun isNumber(o: Any?): Boolean = o is Number @@ -430,7 +411,7 @@ actual class Platform { actual fun isScalar(o: Any?): Boolean = o == null || o is Number || o is String || o is Boolean @JvmStatic - actual fun isInteger(o: Any?): Boolean = o is Byte || o is Short || o is Int || o is Long || o is JvmInt64 + actual fun isInteger(o: Any?): Boolean = o is Byte || o is Short || o is Int || o is Long @JvmStatic actual fun isDouble(o: Any?): Boolean = o is Double @@ -473,7 +454,6 @@ actual class Platform { is Short -> obj is Int -> obj is Long -> obj - is Int64 -> obj is Float -> obj is Double -> obj is String -> obj @@ -579,10 +559,10 @@ actual class Platform { actual val intKlass: KClass = Int::class /** - * The KClass for [Int64]. + * The KClass for [Long]. */ @JvmField - actual val int64Klass: KClass = Int64::class + actual val int64Klass: KClass = Long::class /** * The KClass for [Double]. @@ -725,20 +705,20 @@ actual class Platform { * @return The current epoch milliseconds. */ @JvmStatic - actual fun currentMillis(): Int64 = longToInt64(System.currentTimeMillis()) + actual fun currentMillis(): Long = System.currentTimeMillis() /** * Returns the current epoch microseconds. * @return current epoch microseconds. */ @JvmStatic - actual fun currentMicros(): Int64 = longToInt64(epochMicros + ((System.nanoTime() - startNanos) / 1000)) + actual fun currentMicros(): Long = epochMicros + ((System.nanoTime() - startNanos) / 1000) /** * Returns the current epoch nanoseconds. * @return current epoch nanoseconds. */ - actual fun currentNanos(): Int64 = longToInt64(epochNanos + (System.nanoTime() - startNanos)) + actual fun currentNanos(): Long = epochNanos + (System.nanoTime() - startNanos) /** * Generates a new random number between 0 and 1 (therefore with 53-bit random bits). diff --git a/here-naksha-lib-base/src/jvmMain/kotlin/naksha/base/PlatformDataViewApi.kt b/here-naksha-lib-base/src/jvmMain/kotlin/naksha/base/PlatformDataViewApi.kt index 6a7b30b2e..f8be44080 100644 --- a/here-naksha-lib-base/src/jvmMain/kotlin/naksha/base/PlatformDataViewApi.kt +++ b/here-naksha-lib-base/src/jvmMain/kotlin/naksha/base/PlatformDataViewApi.kt @@ -57,11 +57,11 @@ actual class PlatformDataViewApi { (view as JvmDataView).setInt32(pos, value, littleEndian) @JvmStatic - actual fun dataview_get_int64(view: PlatformDataView, pos: Int, littleEndian: Boolean): Int64 = + actual fun dataview_get_int64(view: PlatformDataView, pos: Int, littleEndian: Boolean): Long = (view as JvmDataView).getInt64(pos, littleEndian) @JvmStatic - actual fun dataview_set_int64(view: PlatformDataView, pos: Int, value: Int64, littleEndian: Boolean) = + actual fun dataview_set_int64(view: PlatformDataView, pos: Int, value: Long, littleEndian: Boolean) = (view as JvmDataView).setInt64(pos, value, littleEndian) } -} \ No newline at end of file +} diff --git a/here-naksha-lib-handlers/src/jvmMain/java/com/here/naksha/lib/handlers/DefaultStorageHandler.java b/here-naksha-lib-handlers/src/jvmMain/java/com/here/naksha/lib/handlers/DefaultStorageHandler.java index e807d9514..c3bc1cdb7 100644 --- a/here-naksha-lib-handlers/src/jvmMain/java/com/here/naksha/lib/handlers/DefaultStorageHandler.java +++ b/here-naksha-lib-handlers/src/jvmMain/java/com/here/naksha/lib/handlers/DefaultStorageHandler.java @@ -63,7 +63,6 @@ import static com.here.naksha.lib.handlers.DefaultStorageHandler.OperationAttempt.FIRST_ATTEMPT; import static com.here.naksha.lib.handlers.util.RequestTypesUtil.isOnlyWriteCollections; import static java.util.concurrent.TimeUnit.NANOSECONDS; -import static naksha.base.Platform.longToInt64; import static naksha.model.util.RequestHelper.createWriteCollectionsRequest; public class DefaultStorageHandler extends AbstractEventHandler { @@ -143,7 +142,7 @@ private String extractMapIdFromStorageProps(@NotNull IStorage storage) { private void addStorageTimeToStreamInfo(StopWatch storageTimer, NakshaContext ctx) { StreamInfo streamInfo = ctx.getStreamInfo(); if (streamInfo != null) { - streamInfo.addTimeInStorage(longToInt64(NANOSECONDS.toMillis(storageTimer.getNanoTime()))); + streamInfo.addTimeInStorage(NANOSECONDS.toMillis(storageTimer.getNanoTime())); } } diff --git a/here-naksha-lib-heapcache/src/main/java/com/here/naksha/lib/heapcache/HeapCache.java b/here-naksha-lib-heapcache/src/main/java/com/here/naksha/lib/heapcache/HeapCache.java index 8209d4459..b65f12205 100644 --- a/here-naksha-lib-heapcache/src/main/java/com/here/naksha/lib/heapcache/HeapCache.java +++ b/here-naksha-lib-heapcache/src/main/java/com/here/naksha/lib/heapcache/HeapCache.java @@ -18,7 +18,6 @@ */ package com.here.naksha.lib.heapcache; -import naksha.base.Int64; import naksha.base.PlatformMap; import naksha.jbon.IDictManager; import naksha.model.*; @@ -231,7 +230,7 @@ public IDictManager dictManager(@NotNull NakshaContext nakshaContext) { @NotNull @Override - public ILock enterLock(@NotNull String id, @NotNull Int64 waitMillis) { + public ILock enterLock(@NotNull String id, long waitMillis) { return null; } diff --git a/here-naksha-lib-hub/src/jvmMain/java/com/here/naksha/lib/hub/storages/NHAdminStorage.java b/here-naksha-lib-hub/src/jvmMain/java/com/here/naksha/lib/hub/storages/NHAdminStorage.java index e74c5b680..24a1eca3f 100644 --- a/here-naksha-lib-hub/src/jvmMain/java/com/here/naksha/lib/hub/storages/NHAdminStorage.java +++ b/here-naksha-lib-hub/src/jvmMain/java/com/here/naksha/lib/hub/storages/NHAdminStorage.java @@ -18,7 +18,6 @@ */ package com.here.naksha.lib.hub.storages; -import naksha.base.Int64; import naksha.base.PlatformLock; import naksha.base.fn.Fn1; import naksha.base.fn.Fx1; @@ -84,7 +83,7 @@ public int getHardCap() { } @Override - public @NotNull Int64 getNumber() { + public long getNumber() { return psqlStorage.getNumber(); } diff --git a/here-naksha-lib-hub/src/jvmMain/java/com/here/naksha/lib/hub/storages/NHSpaceStorage.java b/here-naksha-lib-hub/src/jvmMain/java/com/here/naksha/lib/hub/storages/NHSpaceStorage.java index 07dee798d..b8bbc1f15 100644 --- a/here-naksha-lib-hub/src/jvmMain/java/com/here/naksha/lib/hub/storages/NHSpaceStorage.java +++ b/here-naksha-lib-hub/src/jvmMain/java/com/here/naksha/lib/hub/storages/NHSpaceStorage.java @@ -35,7 +35,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import naksha.base.Int64; import naksha.base.PlatformLock; import naksha.base.fn.Fn1; import naksha.base.fn.Fx1; @@ -128,7 +127,7 @@ public IReadSession newReadSession(@Nullable SessionOptions options) { } @Override - public @NotNull Int64 getNumber() { + public long getNumber() { throw new UnsupportedOperationException("Unsupported by NHSpaceStorage"); } diff --git a/here-naksha-lib-hub/src/jvmTest/java/com/here/naksha/lib/hub/mock/NHAdminMock.java b/here-naksha-lib-hub/src/jvmTest/java/com/here/naksha/lib/hub/mock/NHAdminMock.java index f30ca9554..512fb324d 100644 --- a/here-naksha-lib-hub/src/jvmTest/java/com/here/naksha/lib/hub/mock/NHAdminMock.java +++ b/here-naksha-lib-hub/src/jvmTest/java/com/here/naksha/lib/hub/mock/NHAdminMock.java @@ -30,7 +30,6 @@ import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; import kotlin.reflect.KClass; -import naksha.base.Int64; import naksha.base.Platform; import naksha.base.PlatformLock; import naksha.jbon.JbDictionary; @@ -166,7 +165,7 @@ public IReadSession newReadSession(@Nullable SessionOptions options) { } @Override - public @NotNull Int64 getNumber() { + public long getNumber() { throw new UnsupportedOperationException("Not yet supported by NHAdminMock"); } diff --git a/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/DictEntry.kt b/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/DictEntry.kt index 44cb17652..0deffc568 100644 --- a/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/DictEntry.kt +++ b/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/DictEntry.kt @@ -27,7 +27,7 @@ data class DictEntry( * - `null` * - `Boolean` * - `Int` - * - `Int64` + * - `Long` * - `Double` * - `String` * - `Map` - with _Any_ again being limited to these types. @@ -35,4 +35,4 @@ data class DictEntry( * @since 3.0.0 */ val value: Any? -) \ No newline at end of file +) diff --git a/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/HeapBook.kt b/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/HeapBook.kt index 43caf0fd9..05751f86e 100644 --- a/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/HeapBook.kt +++ b/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/HeapBook.kt @@ -2,7 +2,6 @@ package naksha.jbon -import naksha.base.Int64 import kotlin.js.JsExport import kotlin.js.JsStatic import kotlin.jvm.JvmOverloads @@ -28,7 +27,7 @@ class HeapBook( @JvmStatic @JsStatic @JvmOverloads - fun copyOf(other: IBook, databaseNumber: Int64? = other.databaseNumber, featureNumber: Int64? = other.featureNumber): HeapBook { + fun copyOf(other: IBook, databaseNumber: Long? = other.databaseNumber, featureNumber: Long? = other.featureNumber): HeapBook { val c = HeapBook(other.bookType) c.id = other.id c.databaseNumber = other.databaseNumber @@ -51,8 +50,8 @@ class HeapBook( } - override var databaseNumber: Int64? = null - override var featureNumber: Int64? = null + override var databaseNumber: Long? = null + override var featureNumber: Long? = null private val _names = mutableListOf() private val _values = mutableListOf() @@ -97,7 +96,7 @@ class HeapBook( * @since 3.0.0 */ @JvmOverloads - fun copy(bookType: BookType = this.bookType, databaseNumber: Int64? = this.databaseNumber, featureNumber: Int64? = this.featureNumber): HeapBook { + fun copy(bookType: BookType = this.bookType, databaseNumber: Long? = this.databaseNumber, featureNumber: Long? = this.featureNumber): HeapBook { val c = HeapBook(bookType) c.databaseNumber = this.databaseNumber c.featureNumber = this.featureNumber diff --git a/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/IBook.kt b/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/IBook.kt index d3251dc92..353a8ec82 100644 --- a/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/IBook.kt +++ b/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/IBook.kt @@ -2,7 +2,6 @@ package naksha.jbon -import naksha.base.Int64 import kotlin.js.JsExport import kotlin.js.JsName @@ -56,18 +55,18 @@ interface IBook { * The database-number of the book, if this is a global book stored in a database. * @since 3.0 */ - val databaseNumber: Int64? + val databaseNumber: Long? /** * The feature-number of the book, if this is a global book stored in a database. * @since 3.0 */ - val featureNumber: Int64? + val featureNumber: Long? /** * Returns the element at the given index. If no such index exists, returns _null_. * @param index the index to query. - * @return the value being one of: `null`, `Boolean`, `Int`, `Int64`, `Double`, `String`, `Map`, or `List`. + * @return the value being one of: `null`, `Boolean`, `Int`, `Long`, `Double`, `String`, `Map`, or `List`. * @since 3.0 */ @JsName("getByIndex") @@ -141,4 +140,4 @@ interface IBook { * @since 3.0.0 */ fun getAllWithHash(hash: Int): List -} \ No newline at end of file +} diff --git a/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/IDictBuilder.kt b/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/IDictBuilder.kt index 093a77ffd..08db0e0d4 100644 --- a/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/IDictBuilder.kt +++ b/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/IDictBuilder.kt @@ -7,7 +7,7 @@ package naksha.jbon interface IDictBuilder : IBook { /** * Append the given value to the end of the dictionary. If the value is already in the dictionary, return the index. - * @param value the value to add, must be any of `null`, `Boolean`, `Int`, `Int64`, `Double`, `String`, `Map`, or `List`. + * @param value the value to add, must be any of `null`, `Boolean`, `Int`, `Long`, `Double`, `String`, `Map`, or `List`. * @return the index of the value (this can differ from [length], if the value is already in the dictionary). * @since 3.0.0 */ @@ -19,4 +19,4 @@ interface IDictBuilder : IBook { * @return the JBON encoded dictionary. */ fun toJBON(id: String?): ByteArray -} \ No newline at end of file +} diff --git a/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/JbDecoder.kt b/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/JbDecoder.kt index 3de5af364..22ada1676 100644 --- a/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/JbDecoder.kt +++ b/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/JbDecoder.kt @@ -627,18 +627,18 @@ open class JbDecoder { * Read the current unit as integer. * @return The value read or _null_, if the current unit is no integer. */ - fun decodeInt64(): Int64? { + fun decodeInt64(): Long? { val leadIn = leadIn() return when (leadIn and ENC_MASK) { ENC_TINY -> when (leadIn and ENC_TINY_MASK) { - ENC_TINY_INT -> Int64((leadIn shl 27) shr 27) + ENC_TINY_INT -> ((leadIn shl 27) shr 27).toLong() else -> null } ENC_MIXED -> when (leadIn) { - ENC_MIXED_SCALAR_INT8 -> Int64(binary.getInt8(pos + 1).toInt()) - ENC_MIXED_SCALAR_INT16 -> Int64(binary.getInt16(pos + 1).toInt()) - ENC_MIXED_SCALAR_INT32 -> Int64(binary.getInt32(pos + 1)) + ENC_MIXED_SCALAR_INT8 -> binary.getInt8(pos + 1).toLong() + ENC_MIXED_SCALAR_INT16 -> binary.getInt16(pos + 1).toLong() + ENC_MIXED_SCALAR_INT32 -> binary.getInt32(pos + 1).toLong() ENC_MIXED_SCALAR_INT64 -> binary.getInt64(pos + 1) else -> null } @@ -653,11 +653,11 @@ open class JbDecoder { * Reads the timestamp if the current unit is a timestamp. * @throws IllegalStateException If the current unit is no timestamp. */ - fun decodeTimestamp(): Int64 { + fun decodeTimestamp(): Long { val view = binary check(unitType() == TYPE_TIMESTAMP) { "Can't read timestamp, unit is ${unitTypeName(unitType())}" } val hi = (view.getInt16(pos + 1).toLong() and 0xffff) shl 32 - return Int64(hi or (view.getInt32(pos + 3).toLong() and 0xffff_ffff)) + return hi or (view.getInt32(pos + 3).toLong() and 0xffff_ffffL) } /** @@ -853,7 +853,7 @@ open class JbDecoder { /** * Read the current unit. - * @return _null_, [Boolean], [Int], [Int64], [Double], [String], [AnyObject] or [Array]. + * @return _null_, [Boolean], [Int], [Long], [Double], [String], [AnyObject] or [Array]. * @throws IllegalStateException If the reader position or the unit-type is invalid. */ fun decodeValue(): Any? { @@ -879,4 +879,4 @@ open class JbDecoder { throw IllegalStateException("Not implemented jbon value type") } } -} \ No newline at end of file +} diff --git a/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/JbDecoder2.kt b/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/JbDecoder2.kt index fa22da436..89485f9d2 100644 --- a/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/JbDecoder2.kt +++ b/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/JbDecoder2.kt @@ -280,7 +280,7 @@ open class JbDecoder2(var globalBook: IBook? = null, var membersBook: IBook? = n JB2_INT64 -> view.getInt64(at + 1) JB2_FLOAT32 -> view.getFloat32(at + 1) JB2_FLOAT64 -> view.getFloat64(at + 1) - JB2_TIMESTAMP, JB2_UINT56 -> view.getInt64(at) and Platform.toInt64(JB2_MASK_56_LOW) + JB2_TIMESTAMP, JB2_UINT56 -> view.getInt64(at) and JB2_MASK_56_LOW JB2_UINT24 -> view.getInt32(at) and JB2_MASK_24_LOW JB2_TUPLE_NUMBER -> { // lead-in at `at`, data starts at `at + 1`: 8 + 4 + 4 + 8 + 8 = 32 bytes diff --git a/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/JbDictionary.kt b/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/JbDictionary.kt index 07fa354c2..602e46e65 100644 --- a/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/JbDictionary.kt +++ b/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/JbDictionary.kt @@ -2,14 +2,13 @@ package naksha.jbon -import naksha.base.Int64 import kotlin.js.ExperimentalJsExport import kotlin.js.JsExport @JsExport class JbDictionary(override val bookType: BookType = BookType.LOCAL_BOOK,) : JbStructDecoder(), IBook { - override var databaseNumber: Int64? = null - override var featureNumber: Int64? = null + override var databaseNumber: Long? = null + override var featureNumber: Long? = null /** * Cached ID of the dictionary, if any. @@ -142,4 +141,4 @@ class JbDictionary(override val bookType: BookType = BookType.LOCAL_BOOK,) : JbS } return -1 } -} \ No newline at end of file +} diff --git a/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/JbEncoder.kt b/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/JbEncoder.kt index 6a8276d5d..771431e7a 100644 --- a/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/JbEncoder.kt +++ b/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/JbEncoder.kt @@ -132,7 +132,7 @@ open class JbEncoder(var global: IBook? = null) : Binary() { */ @JvmStatic @JsStatic - fun sizeOfInt64Encoding(value: Int64): Int { + fun sizeOfInt64Encoding(value: Long): Int { if (value >= Int.MAX_VALUE || value <= Int.MIN_VALUE) return 9 return sizeOfIntEncoding(value.toInt()) } @@ -296,7 +296,7 @@ open class JbEncoder(var global: IBook? = null) : Binary() { * @param value The integer to write. * @return The offset of the value written. */ - fun encodeInt64(value: Int64): Int { + fun encodeInt64(value: Long): Int { if (value >= Int.MIN_VALUE && value <= Int.MAX_VALUE) { return encodeInt32(value.toInt()) } @@ -311,7 +311,7 @@ open class JbEncoder(var global: IBook? = null) : Binary() { * @param value The timestamp to write. * @return The offset of the value written. */ - fun encodeTimestamp(value: Int64): Int { + fun encodeTimestamp(value: Long): Int { val offset = end; writeInt8(ENC_MIXED_SCALAR_TIMESTAMP.toByte()) val hi = (value ushr 32).toShort() @@ -923,8 +923,7 @@ open class JbEncoder(var global: IBook? = null) : Binary() { is Byte -> encodeInt32(value.toInt()) is Short -> encodeInt32(value.toInt()) is Int -> encodeInt32(value) - is Long -> encodeInt64(value.toInt64()) - is Int64 -> encodeInt64(value) + is Long -> encodeInt64(value) is Float -> encodeFloat32(value) is Double -> if (Platform.canBeFloat32(value)) encodeFloat32(value.toFloat()) else encodeFloat64(value) is MapProxy<*, *> -> encodeMap(value as MapProxy) @@ -1041,4 +1040,4 @@ open class JbEncoder(var global: IBook? = null) : Binary() { } return targetArray } -} \ No newline at end of file +} diff --git a/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/JbEncoder2.kt b/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/JbEncoder2.kt index 9b0ee60e8..641184063 100644 --- a/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/JbEncoder2.kt +++ b/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/JbEncoder2.kt @@ -223,7 +223,7 @@ open class JbEncoder2(var global: IBook? = null) : Binary() { } /** Write a 64-bit integer using the smallest JBON2 encoding. */ - fun encodeInt64(value: Int64): Int { + fun encodeInt64(value: Long): Int { if (value >= Int.MIN_VALUE && value <= Int.MAX_VALUE) { return encodeInt32(value.toInt()) } @@ -265,10 +265,10 @@ open class JbEncoder2(var global: IBook? = null) : Binary() { * @param value The value to write; only the lower 56 bits are stored. * @return The offset of the value written. */ - fun encodeUInt56(value: Int64): Int { + fun encodeUInt56(value: Long): Int { val pos = end - val masked = value and Platform.toInt64(JB2_MASK_56_LOW) - val packed = (Platform.toInt64(JB2_UINT56.toLong()) shl 56) or masked + val masked = value and JB2_MASK_56_LOW + val packed = (JB2_UINT56.toLong() shl 56) or masked writeInt64(packed) return pos } @@ -291,10 +291,10 @@ open class JbEncoder2(var global: IBook? = null) : Binary() { * @param value The timestamp to write. * @return The offset of the value written. */ - fun encodeTimestamp(value: Int64): Int { + fun encodeTimestamp(value: Long): Int { val pos = end - val masked = value and Platform.toInt64(JB2_MASK_56_LOW) - val packed = (Platform.toInt64(JB2_TIMESTAMP.toLong()) shl 56) or masked + val masked = value and JB2_MASK_56_LOW + val packed = (JB2_TIMESTAMP.toLong() shl 56) or masked writeInt64(packed) return pos } @@ -315,11 +315,11 @@ open class JbEncoder2(var global: IBook? = null) : Binary() { * @return The offset of the value written. */ fun encodeTupleNumber( - databaseNumber: Int64, + databaseNumber: Long, catalogNumber: Int, collectionNumber: Int, - featureNumber: Int64, - version: Int64 + featureNumber: Long, + version: Long ): Int { val pos = end writeInt8(JB2_TUPLE_NUMBER.toByte()) @@ -867,8 +867,7 @@ open class JbEncoder2(var global: IBook? = null) : Binary() { is Byte -> encodeInt32(value.toInt()) is Short -> encodeInt32(value.toInt()) is Int -> encodeInt32(value) - is Long -> encodeInt64(value.toInt64()) - is Int64 -> encodeInt64(value) + is Long -> encodeInt64(value) is Float -> encodeFloat32(value) is Double -> if (Platform.canBeFloat32(value)) encodeFloat32(value.toFloat()) else encodeFloat64(value) is SpGeometry -> encodeGeometry(value) diff --git a/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/NakshaTxn.kt b/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/NakshaTxn.kt index 3162e2a8b..2c064dd8f 100644 --- a/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/NakshaTxn.kt +++ b/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/NakshaTxn.kt @@ -2,7 +2,6 @@ package naksha.jbon -import naksha.base.Int64 import kotlin.js.ExperimentalJsExport import kotlin.js.JsExport @@ -15,22 +14,22 @@ import kotlin.js.JsExport */ @JsExport @Deprecated("Please use new class from lib-model", level = DeprecationLevel.WARNING) -class NakshaTxn(val value: Int64) : Comparable { +class NakshaTxn(val value: Long) : Comparable { companion object NakshaTxnCompanion { /** * The minimum value of the sequence, so just zero. */ - val SEQ_MIN = Int64(0) + const val SEQ_MIN = 0L /** * The maximum value for the sequence, can be used as well as bitmask. */ - val SEQ_MAX = Int64(0x0000_03ff_ffff_ffff) + const val SEQ_MAX = 0x0000_03ff_ffff_ffffL /** * The value to be added to calculate the end of a day. */ - val SEQ_NEXT = Int64(0x0000_0400_0000_0000) + const val SEQ_NEXT = 0x0000_0400_0000_0000L /** * Create a transaction number from its parts. @@ -39,8 +38,8 @@ class NakshaTxn(val value: Int64) : Comparable { * @param day The day to encode, between 1 and 31. * @param seq The sequence in the day, between 0 and 2^42-1. */ - fun of(year: Int, month: Int, day: Int, seq: Int64): NakshaTxn = - NakshaTxn((Int64(year) shl 51) or (Int64(month) shl 47) or (Int64(day) shl 42) + seq) + fun of(year: Int, month: Int, day: Int, seq: Long): NakshaTxn = + NakshaTxn((year.toLong() shl 51) or (month.toLong() shl 47) or ((day.toLong() shl 42) + seq)) } private var _year = -1 @@ -61,8 +60,8 @@ class NakshaTxn(val value: Int64) : Comparable { return _day } - private var _seq: Int64? = null - fun seq(): Int64 { + private var _seq: Long? = null + fun seq(): Long { if (_seq == null) _seq = value and SEQ_MAX return _seq!! } @@ -81,14 +80,13 @@ class NakshaTxn(val value: Int64) : Comparable { } override fun equals(other: Any?): Boolean { - if (other is Int64) return value eq other - if (other is NakshaTxn) return value eq other.value + if (other is Long) return value == other + if (other is NakshaTxn) return value == other.value return false } override fun compareTo(other: NakshaTxn): Int { - val diff = value - other.value - return if (diff eq 0) 0 else if (diff < 0) -1 else 1 + return value.compareTo(other.value) } override fun hashCode(): Int { @@ -118,4 +116,4 @@ class NakshaTxn(val value: Int64) : Comparable { * @return The UUID for this new feature state. */ fun newFeatureUuid(storageId: String, collectionId: String, uid: Int): NakshaUuid = NakshaUuid(storageId, collectionId, year(), month(), day(), seq(), uid) -} \ No newline at end of file +} diff --git a/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/NakshaUuid.kt b/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/NakshaUuid.kt index f3fe7707a..6e2a39195 100644 --- a/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/NakshaUuid.kt +++ b/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/NakshaUuid.kt @@ -2,7 +2,6 @@ package naksha.jbon -import naksha.base.Int64 import kotlin.js.ExperimentalJsExport import kotlin.js.JsExport import kotlin.jvm.JvmStatic @@ -12,7 +11,7 @@ import kotlin.jvm.JvmStatic */ @JsExport @Deprecated("Please use new class from lib-model", level = DeprecationLevel.WARNING) -class NakshaUuid(val storageId: String, val collectionId: String, val year: Int, val month: Int, val day: Int, val seq: Int64, val uid: Int) { +class NakshaUuid(val storageId: String, val collectionId: String, val year: Int, val month: Int, val day: Int, val seq: Long, val uid: Int) { private lateinit var string : String companion object NakshaUuidCompanion { @JvmStatic @@ -25,13 +24,13 @@ class NakshaUuid(val storageId: String, val collectionId: String, val year: Int, values[2].toInt(), values[3].toInt(), values[4].toInt(), - Int64( values[5].toLong()), + values[5].toLong(), values[6].toInt(), ) } @JvmStatic - fun from(storageId: String, collectionId: String, txn: Int64, uid: Int): NakshaUuid { + fun from(storageId: String, collectionId: String, txn: Long, uid: Int): NakshaUuid { val nakshaTxn = NakshaTxn(txn) return NakshaUuid( storageId, @@ -57,4 +56,4 @@ class NakshaUuid(val storageId: String, val collectionId: String, val year: Int, if (!this::string.isInitialized) string = "$storageId:$collectionId:$year:$month:$day:$seq:$uid" return string } -} \ No newline at end of file +} diff --git a/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/NkStorageRow.kt b/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/NkStorageRow.kt index 0eaa81c02..98db67d2f 100644 --- a/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/NkStorageRow.kt +++ b/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/NkStorageRow.kt @@ -2,7 +2,6 @@ package naksha.jbon -import naksha.base.Int64 import kotlin.js.ExperimentalJsExport import kotlin.js.JsExport @@ -27,5 +26,5 @@ data class NkStorageRow( val id : String, val uuid : String, val type : String, - val fnv1aHash : Int64 + val fnv1aHash : Long ) diff --git a/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/XyzVersion.kt b/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/XyzVersion.kt index 5d82f3c64..73550432e 100644 --- a/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/XyzVersion.kt +++ b/here-naksha-lib-jbon/src/commonMain/kotlin/naksha/jbon/XyzVersion.kt @@ -1,7 +1,6 @@ @file:OptIn(ExperimentalJsExport::class) package naksha.jbon -import naksha.base.Int64 import kotlin.js.ExperimentalJsExport import kotlin.js.JsExport @@ -26,7 +25,7 @@ class XyzVersion(val major: Int, val minor: Int, val revision: Int) : Comparable s.substring(minorEnd + 1).toInt()) } - fun fromBigInt(v: Int64) : XyzVersion { + fun fromBigInt(v: Long) : XyzVersion { val major = (v ushr 32).toInt() val minor = (v.toInt() ushr 16) and 0xffff val revision = v.toInt() and 0xffff @@ -34,8 +33,8 @@ class XyzVersion(val major: Int, val minor: Int, val revision: Int) : Comparable } } - fun toBigInt() : Int64 { - return (Int64(major) shl 32) or Int64(minor shl 16) or Int64(revision) + fun toBigInt() : Long { + return (major.toLong() shl 32) or (minor.toLong() shl 16) or revision.toLong() } override fun compareTo(other: XyzVersion): Int { @@ -57,4 +56,4 @@ class XyzVersion(val major: Int, val minor: Int, val revision: Int) : Comparable override fun toString() : String { return "$major.$minor.$revision" } -} \ No newline at end of file +} diff --git a/here-naksha-lib-jbon/src/commonTest/kotlin/naksha/jbon/JbCoreTest.kt b/here-naksha-lib-jbon/src/commonTest/kotlin/naksha/jbon/JbCoreTest.kt index cccd3d893..83c20b74a 100644 --- a/here-naksha-lib-jbon/src/commonTest/kotlin/naksha/jbon/JbCoreTest.kt +++ b/here-naksha-lib-jbon/src/commonTest/kotlin/naksha/jbon/JbCoreTest.kt @@ -807,7 +807,7 @@ class JbCoreTest { @Test fun testJbonTimestamp() { val nowLong = 1707491351417L - val nowBigInt64 = Int64(nowLong) + val nowBigInt64 = nowLong val builder = JbEncoder(1024) val reader = JbDecoder().mapBinary(builder, 0, 1024) builder.encodeTimestamp(nowBigInt64) @@ -817,14 +817,14 @@ class JbCoreTest { assertEquals(nowLong.toInt(), builder.getInt32(reader.pos + 3)) assertTrue(reader.isTimestamp()) val ts = reader.decodeTimestamp() - assertEquals(nowLong, ts.toLong()) + assertEquals(nowLong, ts) assertEquals(7, reader.unitSize()) assertEquals(7, builder.clear()) } @Test fun testTimestamp() { - val millis = Int64(1707985967244) + val millis = 1707985967244L val ts = Timestamp.fromMillis(millis) assertEquals(millis, ts.ts) assertEquals(2024, ts.year) diff --git a/here-naksha-lib-jbon/src/commonTest/kotlin/naksha/jbon/Jbon2Test.kt b/here-naksha-lib-jbon/src/commonTest/kotlin/naksha/jbon/Jbon2Test.kt index 79c6209f1..6f646413a 100644 --- a/here-naksha-lib-jbon/src/commonTest/kotlin/naksha/jbon/Jbon2Test.kt +++ b/here-naksha-lib-jbon/src/commonTest/kotlin/naksha/jbon/Jbon2Test.kt @@ -241,45 +241,45 @@ class Jbon2Test { @Test fun testInt64FirstAboveInt32Max() { - val v = (Int.MAX_VALUE.toLong() + 1L).toInt64() + val v = Int.MAX_VALUE.toLong() + 1L val enc = singleEncode(v) assertEquals(9, enc.end, "Int64 above Int32 max must be 9 bytes") assertEquals(JB2_INT64.toByte(), enc.getInt8(0), "lead-in must be INT64") val decoded = singleDecode(enc) - assertIs(decoded, "decoded value must be Int64") - assertEquals(Int.MAX_VALUE.toLong() + 1L, decoded.toLong()) + assertIs(decoded, "decoded value must be Long") + assertEquals(Int.MAX_VALUE.toLong() + 1L, decoded) } @Test fun testInt64FirstBelowInt32Min() { - val v = (Int.MIN_VALUE.toLong() - 1L).toInt64() + val v = Int.MIN_VALUE.toLong() - 1L val enc = singleEncode(v) assertEquals(9, enc.end) val decoded = singleDecode(enc) - assertIs(decoded) - assertEquals(Int.MIN_VALUE.toLong() - 1L, decoded.toLong()) + assertIs(decoded) + assertEquals(Int.MIN_VALUE.toLong() - 1L, decoded) } @Test fun testInt64MaxValue() { - val enc = singleEncode(Long.MAX_VALUE.toInt64()) + val enc = singleEncode(Long.MAX_VALUE) assertEquals(9, enc.end) - val decoded = singleDecode(enc) as Int64 - assertEquals(Long.MAX_VALUE, decoded.toLong()) + val decoded = singleDecode(enc) as Long + assertEquals(Long.MAX_VALUE, decoded) } @Test fun testInt64MinValue() { - val enc = singleEncode(Long.MIN_VALUE.toInt64()) + val enc = singleEncode(Long.MIN_VALUE) assertEquals(9, enc.end) - val decoded = singleDecode(enc) as Int64 - assertEquals(Long.MIN_VALUE, decoded.toLong()) + val decoded = singleDecode(enc) as Long + assertEquals(Long.MIN_VALUE, decoded) } /** Values inside Int32 range must NOT use the 9-byte Int64 encoding. */ @Test fun testInt64FallsBackToInt32ForSmallValues() { - val enc = singleEncode(Int.MAX_VALUE.toLong().toInt64()) + val enc = singleEncode(Int.MAX_VALUE.toLong()) assertEquals(5, enc.end, "Int.MAX_VALUE as Long should be encoded as Int32 (5 bytes), not Int64") assertEquals(Int.MAX_VALUE, singleDecode(enc)) } @@ -795,7 +795,7 @@ class Jbon2Test { @Test fun testTupleNumberHead() { - val tn = TupleNumber(Int64(0), 0, 0, Int64(0), Version.HEAD.number) + val tn = TupleNumber(0L, 0, 0, 0L, Version.HEAD.number) val enc = singleEncode(tn) assertEquals(33, enc.end, "TupleNumber must be exactly 33 bytes") assertEquals(JB2_TUPLE_NUMBER.toByte(), enc.getInt8(0), "lead-in must be TUPLE_NUMBER") @@ -809,13 +809,13 @@ class Jbon2Test { @Test fun testTupleNumberRealisticValues() { - // Simulate realistic values: large Int64 storage number, negative catalog/collection from MD5 hash + // Simulate realistic values: large 64-bit storage number, negative catalog/collection from MD5 hash val tn = TupleNumber( - databaseNumber = Int64(0x8000000012345678UL.toLong()), + databaseNumber = 0x8000000012345678UL.toLong(), catalogNumber = -1234567890, collectionNumber = -987654321, - featureNumber = Int64(0x80000000ABCDEF00UL.toLong()), - version = Int64(42) + featureNumber = 0x80000000ABCDEF00UL.toLong(), + version = 42L ) val enc = singleEncode(tn) assertEquals(33, enc.end) @@ -831,11 +831,11 @@ class Jbon2Test { @Test fun testTupleNumberAllExtremes() { val tn = TupleNumber( - databaseNumber = Int64(Long.MIN_VALUE), + databaseNumber = Long.MIN_VALUE, catalogNumber = Int.MIN_VALUE, collectionNumber = Int.MAX_VALUE, - featureNumber = Int64(Long.MAX_VALUE), - version = Int64(Long.MIN_VALUE) + featureNumber = Long.MAX_VALUE, + version = Long.MIN_VALUE ) val enc = singleEncode(tn) assertEquals(33, enc.end) @@ -850,7 +850,7 @@ class Jbon2Test { @Test fun testTupleNumberUnitSize() { // Verify that JbDecoder2.unitSize() correctly reports 33 bytes for TUPLE_NUMBER - val tn = TupleNumber(Int64(1), 2, 3, Int64(4), Int64(5)) + val tn = TupleNumber(1L, 2, 3, 4L, 5L) val enc = singleEncode(tn) val dec = JbDecoder2() val bin = Binary() @@ -864,11 +864,11 @@ class Jbon2Test { @Test fun testTupleNumberExplicitEncodeDecode() { // Test the low-level encodeTupleNumber/decode path directly, bypassing encodeValue - val db = Int64(100) + val db = 100L val cat = -200 val col = 300 - val feat = Int64(-400) - val ver = Int64(500) + val feat = -400L + val ver = 500L val enc = JbEncoder2() enc.encodeTupleNumber(db, cat, col, feat, ver) @@ -959,7 +959,7 @@ class Jbon2Test { @Test fun testJsonConversionLargeInt() { - // 2147483648 = Int.MAX_VALUE + 1; decoded as Int or Int64; either way must appear as a number. + // 2147483648 = Int.MAX_VALUE + 1; decoded as Int or Long; either way must appear as a number. val f = roundTrip("""{"id":"x","properties":{"big":2147483648}}""") val json = Platform.toJSON(f) assertTrue(json.contains("2147483648"), "large integer must appear numerically in JSON, not as a class name") diff --git a/here-naksha-lib-jbon/src/jvmTest/kotlin/naksha/jbon/Jbon2MembersTest.kt b/here-naksha-lib-jbon/src/jvmTest/kotlin/naksha/jbon/Jbon2MembersTest.kt index 02d4f7dd1..33ede1776 100644 --- a/here-naksha-lib-jbon/src/jvmTest/kotlin/naksha/jbon/Jbon2MembersTest.kt +++ b/here-naksha-lib-jbon/src/jvmTest/kotlin/naksha/jbon/Jbon2MembersTest.kt @@ -2,7 +2,6 @@ package naksha.jbon import naksha.base.AnyObject import naksha.base.Binary -import naksha.base.Int64 import naksha.base.MapProxy import naksha.base.Platform import naksha.geo.GeoUtil @@ -32,8 +31,8 @@ class Jbon2MembersTest { private class ListDict(private val entries: List) : IBook { override val id: String? = null override val bookType: BookType = BookType.MEMBER_BOOK - override val databaseNumber: Int64? = null - override val featureNumber: Int64? = null + override val databaseNumber: Long? = null + override val featureNumber: Long? = null override val length: Int get() = entries.size override fun get(index: Int): Any? = entries.getOrNull(index) override fun indexOfString(string: String): Int = entries.indexOfFirst { it == string } diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/AbstractStorage.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/AbstractStorage.kt index dedb154ff..173201719 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/AbstractStorage.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/AbstractStorage.kt @@ -7,14 +7,12 @@ import kotlinx.datetime.toLocalDateTime import naksha.base.Action import naksha.base.Action.Action_C.VERSION import naksha.base.AtomicRef -import naksha.base.Int64 import naksha.base.Platform import naksha.base.NakshaError.NakshaErrorCompanion.ILLEGAL_ARGUMENT import naksha.base.NakshaError.NakshaErrorCompanion.UNINITIALIZED import naksha.base.NakshaException import naksha.base.TupleNumber import naksha.base.Version -import naksha.base.toInt64 import naksha.model.Naksha.NakshaCompanion.catalogNumber import naksha.model.Naksha.NakshaCompanion.collectionNumber import naksha.model.Naksha.NakshaCompanion.databaseNumber @@ -50,7 +48,7 @@ abstract class AbstractStorage : IStorage { */ protected var configRef: AtomicRef = AtomicRef(null) private var _id: String? = null - private var _number: Int64? = null + private var _number: Long? = null override val config: CONFIG get() = configRef.get() ?: throwUninitialized() @@ -58,7 +56,7 @@ abstract class AbstractStorage : IStorage { override val id: String get() = _id ?: throwUninitialized() - override val number: Int64 + override val number: Long get() = _number ?: throwUninitialized() override var hardCap: Int = 16777216 @@ -119,8 +117,8 @@ abstract class AbstractStorage : IStorage { * @since 3.0 * @throws naksha.base.NakshaException with error [UNINITIALIZED][naksha.base.NakshaError.UNINITIALIZED], if the storage failed to initialize. */ - protected open fun newVirtualTupleNumber(catalogId: String, collectionId: String, featureId: String, version: Int64, action: Action): TupleNumber { - val v = ((version.toLong() and -4L) or action.longValue).toInt64() + protected open fun newVirtualTupleNumber(catalogId: String, collectionId: String, featureId: String, version: Long, action: Action): TupleNumber { + val v = (version and -4L) or action.longValue return TupleNumber(databaseNumber(id), catalogNumber(catalogId), collectionNumber(collectionId), featureNumber(featureId), v) } @@ -131,7 +129,7 @@ abstract class AbstractStorage : IStorage { * @since 3.0 * @see newVirtualVersion */ - protected open val nextVirtualVersion = Platform.newAtomicInt64(Version.now(0L.toInt64(), VERSION).number) + protected open val nextVirtualVersion = Platform.newAtomicInt64(Version.now(0L, VERSION).number) /** * Creates a new JVM local unique transaction number, aka virtual version. @@ -144,11 +142,11 @@ abstract class AbstractStorage : IStorage { protected open fun newVirtualVersion(): Version { // More reliable tailrec. while (true) { - val version = Version(nextVirtualVersion.getAndAdd(4L.toInt64()) ) + val version = Version(nextVirtualVersion.getAndAdd(4L)) // getAndAdd uses a memory-fence, therefore `now` is guaranteed to be read after the version! val now: LocalDateTime = Clock.System.now().toLocalDateTime(TimeZone.UTC) if (version.isBehind(now.year, now.month.number, now.day)) { - val newVersion = Version.auto(now.year, now.month.number, now.day, 0L.toInt64(), VERSION) + val newVersion = Version.auto(now.year, now.month.number, now.day, 0L, VERSION) if (nextVirtualVersion.compareAndSet(version.number + 4, newVersion.number + 4)) return newVersion // Fail, concurrent increment, repeat. continue @@ -211,4 +209,4 @@ abstract class AbstractStorage : IStorage { protected open fun dropCache() { // Naksha.cache.removedStorage(this) } -} \ No newline at end of file +} diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/BinaryUtil.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/BinaryUtil.kt index d2c160d0a..2b96c1299 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/BinaryUtil.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/BinaryUtil.kt @@ -2,7 +2,6 @@ package naksha.model -import naksha.base.Int64 import naksha.base.PlatformDataView import naksha.base.PlatformDataViewApi.PlatformDataViewApiCompanion.dataview_get_int16 import naksha.base.PlatformDataViewApi.PlatformDataViewApiCompanion.dataview_get_int32 @@ -157,9 +156,9 @@ class BinaryUtil private constructor() { */ @JvmStatic @JsStatic - fun readTimestamp(view: PlatformDataView, offset: Int): Int64 - = (Int64(dataview_get_int16(view, offset).toInt() and 0xffff) shl 16) or - (Int64(dataview_get_int32(view, offset + 2)) and Int64(0xffff_ffffL)) + fun readTimestamp(view: PlatformDataView, offset: Int): Long + = ((dataview_get_int16(view, offset).toLong() and 0xffffL) shl 16) or + (dataview_get_int32(view, offset + 2).toLong() and 0xffff_ffffL) /** * Read a binary encoded [naksha.base.TupleNumber]; can be used to fetch four encodings: @@ -182,13 +181,13 @@ class BinaryUtil private constructor() { fun readTupleNumber( view: PlatformDataView, offset: Int, - storageNumber: Int64? = null, + storageNumber: Long? = null, mapNumber: Int? = null, collectionNumber: Int? = null, - featureNumber: Int64? = null + featureNumber: Long? = null ): TupleNumber? { var pos = if (offset >= 0) offset else return null - val sn: Int64 // storage-number + val sn: Long // storage-number if (storageNumber == null) { sn = dataview_get_int64(view, pos) pos += 8 @@ -206,7 +205,7 @@ class BinaryUtil private constructor() { pos += 4 } else cn = collectionNumber - val fn: Int64 // feature-number + val fn: Long // feature-number if (featureNumber == null) { fn = dataview_get_int64(view, pos) pos += 8 @@ -215,4 +214,4 @@ class BinaryUtil private constructor() { return TupleNumber(sn, mn, cn, fn, txn) } } -} \ No newline at end of file +} diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/IStorage.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/IStorage.kt index 86506b5e2..b50137c2b 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/IStorage.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/IStorage.kt @@ -2,7 +2,6 @@ package naksha.model -import naksha.base.Int64 import naksha.base.PlatformLock import naksha.base.fn.Fn1 import naksha.base.fn.Fx1 @@ -58,7 +57,7 @@ interface IStorage : IDictReader { * @since 3.0 * @throws naksha.base.NakshaException with error [UNINITIALIZED][naksha.base.NakshaError.UNINITIALIZED], if the storage failed to initialize. */ - val number: Int64 + val number: Long /** * The hard-cap _(max result size)_ of the storage. No result-set every can become bigger than this amount of features. @@ -143,4 +142,4 @@ interface IStorage : IDictReader { val session = newReadSession(options) session.use { lambda.call(session) } } -} \ No newline at end of file +} diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/ITupleCache.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/ITupleCache.kt index 9c4a3d69e..eb078627a 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/ITupleCache.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/ITupleCache.kt @@ -2,7 +2,6 @@ package naksha.model -import naksha.base.Int64 import naksha.base.TupleNumber import naksha.jbon.IDictReader import naksha.model.request.FeatureTuple @@ -30,7 +29,7 @@ interface ITupleCache { * * @since 3.0 */ - val latencyInMicros: Int64 + val latencyInMicros: Long /** * Tries to read a single tuple from the cache. @@ -105,7 +104,7 @@ interface ITupleCache { * @param storageNumber the storage-number of the storage from which to query dictionaries. * @return the [dictionary reader][IDictReader] for the requested storage, if any is available. */ - fun getDictReader(storageNumber: Int64): IDictReader? + fun getDictReader(storageNumber: Long): IDictReader? /** * Removes all cache entries (clear the cache). @@ -135,4 +134,4 @@ interface ITupleCache { * @since 3.0 */ fun gc() -} \ No newline at end of file +} diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/LibModel.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/LibModel.kt index 605e866fa..fd8fe16cb 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/LibModel.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/LibModel.kt @@ -5,7 +5,6 @@ // - jn Java at the class naksha.model.LibModelKt.{name} package naksha.model -import naksha.base.Int64 import naksha.base.PlatformUtil.PlatformUtilCompanion.MILLISECOND import naksha.base.PlatformUtil.PlatformUtilCompanion.MILLIS_TO_MICROS import kotlin.js.ExperimentalJsStatic @@ -30,35 +29,35 @@ const val ACTION_DELETE = 2 * @since 3.0 */ @JvmField -val LATENCY_STORAGE = Int64(200) * MILLISECOND * MILLIS_TO_MICROS +val LATENCY_STORAGE = 200L * MILLISECOND * MILLIS_TO_MICROS /** * The default latency to use for S3 buckets, being 100,000 microseconds (aka 100 milliseconds). * @since 3.0 */ @JvmField -val LATENCY_S3 = Int64(100) * MILLISECOND * MILLIS_TO_MICROS +val LATENCY_S3 = 100L * MILLISECOND * MILLIS_TO_MICROS /** * The default latency to use for Redis including some network latency, being 10,000 microseconds (aka 10 milliseconds). * @since 3.0 */ @JvmField -val LATENCY_REDIS_REMOTE = Int64(10) * MILLISECOND * MILLIS_TO_MICROS +val LATENCY_REDIS_REMOTE = 10L * MILLISECOND * MILLIS_TO_MICROS /** * The default latency to use for a local Redis or with ultra-fast networking, being 1,000 microseconds (aka 1 millisecond). * @since 3.0 */ @JvmField -val LATENCY_REDIS_LOCAL = Int64(1) * MILLISECOND * MILLIS_TO_MICROS +val LATENCY_REDIS_LOCAL = 1L * MILLISECOND * MILLIS_TO_MICROS /** * The default latency to use for in-memory caching, being 0 microsecond. * @since 3.0 */ @JvmField -val LATENCY_MEMORY = Int64(0) +val LATENCY_MEMORY = 0L /** * The default feature encoding to be used by all storages — see [Naksha.DEFAULT_DATA_ENCODING]. @@ -147,4 +146,3 @@ const val NO_CACHE_CLEAR: FetchMode = NO_CACHE_BIT.inv() * @since 3.0.0 */ const val FETCH_MASK: FetchMode = 31 - diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/Naksha.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/Naksha.kt index 6b4c5612b..4f98a05e9 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/Naksha.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/Naksha.kt @@ -186,7 +186,7 @@ class Naksha private constructor() { */ @JsStatic @JvmStatic - fun databaseNumber(id: String): Int64 = featureNumber(id) + fun databaseNumber(id: String): Long = featureNumber(id) /** * A method to calculate a valid catalog-number from the catalog-id. @@ -258,9 +258,9 @@ class Naksha private constructor() { */ @JsStatic @JvmStatic - fun featureNumber(id: String): Int64 { + fun featureNumber(id: String): Long { val numericId = featureNumberAsLong(id) - return if (numericId >= 0L) numericId.toInt64() else featureNumberAsHash(id) + return if (numericId >= 0L) numericId else featureNumberAsHash(id) } /** @@ -289,7 +289,7 @@ class Naksha private constructor() { */ @JsStatic @JvmStatic - fun featureNumberAsHash(id: String): Int64 { + fun featureNumberAsHash(id: String): Long { val md5 = hashId(id) return md5.getInt64(8) or INT64_SIGN_BIT } @@ -312,49 +312,43 @@ class Naksha private constructor() { @JsName("isAutoNumber64") @JsStatic @JvmStatic - fun isAutoNumber(number: Int64): Boolean = (number and INT64_SIGN_BIT) == INT64_SIGN_BIT + fun isAutoNumber(number: Long): Boolean = (number and INT64_SIGN_BIT) == INT64_SIGN_BIT /** * `0x8000_0000_0000_0000`, should be `-9223372036854775808`, but this does not work in Kotlin, only `-9223372036854775807 -1`? * - See [programmer calculator](https://devtools.calckit.io/programmer-calculator) */ - @JvmStatic - internal val INT64_SIGN_BIT = Int64(Long.MIN_VALUE) + internal const val INT64_SIGN_BIT = Long.MIN_VALUE /** * `0x7fff_ffff_ffff_ffff` * - See [programmer calculator](https://devtools.calckit.io/programmer-calculator) */ - @JvmStatic - internal val INT64_CLEAR_SIGN_BIT = Int64(0x7fff_ffff_ffff_ffff) + internal const val INT64_CLEAR_SIGN_BIT = 0x7fff_ffff_ffff_ffffL /** * `0x0000_0000_0000_ffff` * - See [programmer calculator](https://devtools.calckit.io/programmer-calculator) */ - @JvmStatic - internal val INT64_CLEAR_HIGH48 = Int64(0x0000_0000_0000_ffff) + internal const val INT64_CLEAR_HIGH48 = 0x0000_0000_0000_ffffL /** * `0x0000_0000_ffff_ffff` aka `4294967295` * - See [programmer calculator](https://devtools.calckit.io/programmer-calculator) */ - @JvmStatic - internal val INT64_CLEAR_HIGH32 = Int64(4294967295) + internal const val INT64_CLEAR_HIGH32 = 4294967295L /** * `0xff00_0000_0000_0000` aka `-72057594037927936` * - See [programmer calculator](https://devtools.calckit.io/programmer-calculator) */ - @JvmStatic - internal val INT64_CLEAR_HIGH8 = Int64(-72057594037927936) + internal const val INT64_CLEAR_HIGH8 = -72057594037927936L /** * `0xffff_ffff_ffff_0000` aka `-65536` * - See [programmer calculator](https://devtools.calckit.io/programmer-calculator) */ - @JvmStatic - internal val INT64_CLEAR_LOW16 = Int64(-65536) + internal const val INT64_CLEAR_LOW16 = -65536L /** * Returns the partition-number from the given feature-id. @@ -379,7 +373,7 @@ class Naksha private constructor() { */ @JsStatic @JvmStatic - fun partitionNumber(featureNumber: Int64): Int = featureNumber.toInt() and 0xffff + fun partitionNumber(featureNumber: Long): Int = featureNumber.toInt() and 0xffff /** * Increment a 64-bit number _(storage- or feature-number)_ programmatically in case of collision, and return the _alternative_ number, derived deterministically from the given number. This method implements the same behavior as the SQL function `naksha_alt64`. @@ -395,7 +389,7 @@ class Naksha private constructor() { */ @JsStatic @JvmStatic - fun alternativeInt64(number: Int64): Int64 + fun alternativeInt64(number: Long): Long = ((number + 65536) and INT64_CLEAR_LOW16) or (number and INT64_CLEAR_HIGH48) or INT64_SIGN_BIT /** @@ -475,7 +469,7 @@ class Naksha private constructor() { * @since 3.0 */ @JvmField - internal val storagesByNumber = AtomicMap>() + internal val storagesByNumber = AtomicMap>() /** * All registered storages by [storage-id][IStorage.id]. @@ -521,7 +515,7 @@ class Naksha private constructor() { */ @JvmStatic @JsStatic - fun getStorageByNumber(storageNumber: Int64): IStorage? = storagesByNumber[storageNumber] + fun getStorageByNumber(storageNumber: Long): IStorage? = storagesByNumber[storageNumber] /** * Returns the storage for the given tuple-number. @@ -628,7 +622,7 @@ class Naksha private constructor() { */ @JvmStatic @JsStatic - fun useStorageByNumber(storageNumber: Int64): IStorage = storagesByNumber[storageNumber] + fun useStorageByNumber(storageNumber: Long): IStorage = storagesByNumber[storageNumber] ?: throw NakshaException(STORAGE_NOT_FOUND, "No storage found for storage-number: $storageNumber") /** diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/NakshaContext.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/NakshaContext.kt index e0362facb..3ae88a65a 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/NakshaContext.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/NakshaContext.kt @@ -275,7 +275,7 @@ open class NakshaContext protected constructor( /** * When calculating the hash of a feature, a function to be called for every property to hash. * - * The function receives the feature that is being hashed, the current path, and the value to be hashed (will be _null_, _String_, _Int_, _Int64_, _Double_ or _Boolean_). It should return _true_, when the value should be part of the hash; _false_ otherwise. + * The function receives the feature that is being hashed, the current path, and the value to be hashed (will be _null_, _String_, _Int_, _Long_, _Double_ or _Boolean_). It should return _true_, when the value should be part of the hash; _false_ otherwise. */ open var excludeFn: Fn3, Any?>? = null get() = if (field == null) defaultExcludeFn.get() else field @@ -360,7 +360,7 @@ open class NakshaContext protected constructor( * relative timestamps (time since start of a request). */ @JvmField - val startMicros: Int64 = Platform.currentMicros() + val startMicros: Long = Platform.currentMicros() /** * Attaches this context to the current thread. diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/NakshaVersion.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/NakshaVersion.kt index 177bace91..4c393f9c7 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/NakshaVersion.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/NakshaVersion.kt @@ -20,7 +20,6 @@ package naksha.model -import naksha.base.Int64 import kotlin.js.JsExport import kotlin.js.JsName import kotlin.js.JsStatic @@ -205,9 +204,6 @@ class NakshaVersion( * @param enc the multi-platform 64-bit binary encoding. * @since 3.0 */ - @JsName("fromBigInt") - constructor(enc: Int64) : this(enc.toLong()) - private var _long: Long? = null /** @@ -234,7 +230,7 @@ class NakshaVersion( * @return the 64-bit multi-platform binary encoding of this version. * @since 2.0.3 */ - fun toInt64(): Int64 = Int64(toLong()) + fun toInt64(): Long = toLong() override fun compareTo(other: NakshaVersion): Int { val result = toLong() - other.toLong() diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/PgTx.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/PgTx.kt index db2fb750e..4cf65c159 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/PgTx.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/PgTx.kt @@ -2,7 +2,6 @@ package naksha.model -import naksha.base.Int64 import naksha.base.Version import naksha.jbon.IDictReader import naksha.model.objects.* @@ -32,7 +31,7 @@ open class PgTx private constructor( * @since 3.0 * @see [NakshaStorage.number] */ - val storageNumber: Int64, + val storageNumber: Long, /** * The unique version of the transaction. This value **should be** unique to this transaction. @@ -72,7 +71,7 @@ open class PgTx private constructor( @JsName("storageTxWithStorageNumber") constructor( - storageNumber: Int64, + storageNumber: Long, version: Version, appId: String, author: String?, @@ -100,6 +99,6 @@ open class PgTx private constructor( * The `updated_at` value being used for all [Tuple] created, basically just reads `transaction.time`. * @since 3.0 */ - open val updatedAt: Int64 + open val updatedAt: Long get() = nakshaTx.time } diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/SessionOptions.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/SessionOptions.kt index 3142336d0..0cd65f6b8 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/SessionOptions.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/SessionOptions.kt @@ -69,7 +69,7 @@ data class SessionOptions @JvmOverloads constructor( /** * When calculating the hash of a feature, a function to be called for every property to hash. * - * The function receives the feature that is being hashed, the current path, and the value to be hashed (will be _null_, _String_, _Int_, _Int64_, _Double_ or _Boolean_). It should return _true_, when the value should be part of the hash; _false_ otherwise. + * The function receives the feature that is being hashed, the current path, and the value to be hashed (will be _null_, _String_, _Int_, _Long_, _Double_ or _Boolean_). It should return _true_, when the value should be part of the hash; _false_ otherwise. * @since 3.0 */ @JvmField @@ -203,4 +203,4 @@ data class SessionOptions @JvmOverloads constructor( return from(context, null, useMaster) } } -} \ No newline at end of file +} diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/StoreNumberBits.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/StoreNumberBits.kt index eacd3d790..41927edcc 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/StoreNumberBits.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/StoreNumberBits.kt @@ -2,7 +2,6 @@ package naksha.model -import naksha.base.Int64 import kotlin.js.JsExport import kotlin.js.JsStatic import kotlin.jvm.JvmField @@ -43,7 +42,7 @@ open class StoreNumberBits { */ @JvmField @JsStatic - val PART_NUM_MASK = ((Int64(1) shl PART_NUM_BITS) - Int64(1)) shl PART_NUM_SHIFT + val PART_NUM_MASK = ((1L shl PART_NUM_BITS) - 1L) shl PART_NUM_SHIFT /** * The bitmask to AND combine with [StoreNumber] to clear the value from the [StoreNumber]. @@ -76,7 +75,7 @@ open class StoreNumberBits { */ @JvmField @JsStatic - val COL_NUM_MASK = ((Int64(1) shl COL_NUM_BITS) - Int64(1)) shl COL_NUM_SHIFT + val COL_NUM_MASK = ((1L shl COL_NUM_BITS) - 1L) shl COL_NUM_SHIFT /** * The bitmask to AND combine with [StoreNumber] to clear the value from the [StoreNumber]. @@ -107,7 +106,7 @@ open class StoreNumberBits { */ @JvmField @JsStatic - val MAP_NUM_MASK = ((Int64(1) shl MAP_NUM_BITS) - Int64(1)) shl MAP_NUM_SHIFT + val MAP_NUM_MASK = ((1L shl MAP_NUM_BITS) - 1L) shl MAP_NUM_SHIFT /** * The bitmask to AND combine with [StoreNumber] to clear the value from the [StoreNumber]. @@ -116,4 +115,4 @@ open class StoreNumberBits { @JsStatic val MAP_NUM_CLEAR = MAP_NUM_MASK.inv() } -} \ No newline at end of file +} diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/StreamInfo.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/StreamInfo.kt index f3e6dbcf4..a841904f2 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/StreamInfo.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/StreamInfo.kt @@ -129,7 +129,7 @@ open class StreamInfo() { * @param deltaMillis the amount of milliseconds to add or subtract. * @return this. */ - open fun addTimeInStorage(deltaMillis: Int64): StreamInfo { + open fun addTimeInStorage(deltaMillis: Long): StreamInfo { timeInStorageMs.addAndGet(deltaMillis) return this } @@ -138,7 +138,7 @@ open class StreamInfo() { * Returns the current timer value. * @return the current timer value. */ - open fun getTimeInStorageMs(): Int64 = timeInStorageMs.get() + open fun getTimeInStorageMs(): Long = timeInStorageMs.get() /** * Internally used to print a value within [toColonSeparatedString]. @@ -163,4 +163,4 @@ open class StreamInfo() { sb.append(TIME_IN_STORAGE).append('=').append(getTimeInStorageMs()) return sb.toString() } -} \ No newline at end of file +} diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TagMap.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TagMap.kt index 45deb0eec..f53f0fde7 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TagMap.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TagMap.kt @@ -3,7 +3,6 @@ package naksha.model import naksha.base.ITagMap -import naksha.base.Int64 import naksha.base.MapProxy import naksha.base.NakshaError import naksha.base.NakshaException @@ -62,4 +61,4 @@ class TagMap() : MapProxy(String::class, Any::class), ITagMap { "Tag values can only be String, Boolean or Number" ) } -} \ No newline at end of file +} diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/Tuple.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/Tuple.kt index 4de1a199e..6304b3911 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/Tuple.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/Tuple.kt @@ -6,7 +6,6 @@ import naksha.base.Action import naksha.base.AnyList import naksha.base.AnyObject import naksha.base.Guid -import naksha.base.Int64 import naksha.base.ListProxy import naksha.base.MapProxy import naksha.base.Platform.PlatformCompanion.fromJSON @@ -137,8 +136,8 @@ data class Tuple @JvmOverloads constructor( // Read members. val id = idMember.readString(feature) ?: throw illegalArg("Missing 'id' in NakshaFeature") val featureNumber = when (collection.id) { - Naksha.COLLECTIONS_COL_ID -> Int64(Naksha.collectionNumber(id)) - Naksha.CATALOGS_COL_ID -> Int64(Naksha.catalogNumber(id)) + Naksha.COLLECTIONS_COL_ID -> Naksha.collectionNumber(id).toLong() + Naksha.CATALOGS_COL_ID -> Naksha.catalogNumber(id).toLong() else -> Naksha.featureNumber(id) } var prevTn: TupleNumber? @@ -164,7 +163,7 @@ data class Tuple @JvmOverloads constructor( if (colTn.databaseNumber != prevTn.databaseNumber || colTn.catalogNumber != prevTn.catalogNumber || // Note: The feature-number of the collection is the collection-number of the feature stored in it! - colTn.featureNumber != Int64(prevTn.collectionNumber) || + colTn.featureNumber != prevTn.collectionNumber.toLong() || featureNumber != prevTn.featureNumber) { // FORK: Client copied a feature from another collection or changed the `id`. @@ -198,7 +197,7 @@ data class Tuple @JvmOverloads constructor( // The transaction version carries the VERSION sentinel (=3) in its low two action bits; each // feature records its OWN action (CREATE/UPDATE/DELETE) there so the row reads as live. - val version = (session.useTransaction().version.number and Int64(-4)) or Int64(action.intValue) + val version = (session.useTransaction().version.number and -4L) or action.longValue val newTn = TupleNumber( colTn.databaseNumber, colTn.catalogNumber, @@ -415,9 +414,7 @@ data class Tuple @JvmOverloads constructor( return asLong.toInt() } - // TODO: Needs to become Long! private fun coerceInt64(value: Any, featureId: String, memberName: String): Long? = when (value) { - is Int64 -> value.toLong() is Int -> value.toLong() is Long -> value is Short -> value.toLong() @@ -434,7 +431,6 @@ data class Tuple @JvmOverloads constructor( is Double -> value.toFloat() is Int -> value.toFloat() is Long -> value.toFloat() - is Int64 -> value.toLong().toFloat() is Short -> value.toFloat() is Byte -> value.toFloat() else -> null @@ -451,7 +447,6 @@ data class Tuple @JvmOverloads constructor( is Float -> value.toDouble() is Int -> value.toDouble() is Long -> value.toDouble() - is Int64 -> value.toLong().toDouble() is Short -> value.toDouble() is Byte -> value.toDouble() else -> null @@ -538,7 +533,6 @@ data class Tuple @JvmOverloads constructor( is Short -> value.toLong() is Int -> value.toLong() is Long -> value - is Int64 -> value.toLong() is Float -> if (value.isFinite() && value == value.toLong().toFloat()) value.toLong() else null is Double -> if (value.isFinite() && value == value.toLong().toDouble()) value.toLong() else null else -> null @@ -583,9 +577,9 @@ data class Tuple @JvmOverloads constructor( * The next-version at which this tuple was superseded. `NULL`-sentinel indicates the tuple is the current _([Version.HEAD])_ state. * @since 3.0 */ - var nextVersion: Int64 - get() = membersBook[StandardMembers.NextVersion.name] as Int64? ?: Version.HEAD.number - set(version: Int64) { + var nextVersion: Long + get() = membersBook[StandardMembers.NextVersion.name] as Long? ?: Version.HEAD.number + set(version: Long) { val members = this.membersBook if (members is HeapBook) { members.put(StandardMembers.NextVersion.name, version) @@ -622,7 +616,7 @@ data class Tuple @JvmOverloads constructor( val globalBookTn = _globalBookTn if (globalBookTn != null) return globalBookTn val raw = getMember(StandardMembers.GlobalBookFeatureNumber) - if (raw is Int64 || raw is Long) { + if (raw is Long) { TODO("Use the global book number as feature-number, combine with storage-number from tuple, and with admin-catalog, book-collection, version is always HEAD, books are immutable and can not be versioned") } _globalBookTn = globalBookTn @@ -703,12 +697,11 @@ data class Tuple @JvmOverloads constructor( * @since 3.0 */ @JvmOverloads - fun getLong(member: Member, alt: Int64 = Int64(0L)): Int64 = + fun getLong(member: Member, alt: Long = 0L): Long = rawMember(member)?.let { v -> when (v) { - is Int64 -> v - is Long -> Int64(v) - is Number -> Int64(v.toLong()) + is Long -> v + is Number -> v.toLong() else -> alt } } ?: alt @@ -766,11 +759,10 @@ data class Tuple @JvmOverloads constructor( fun getMember(member: Member): Any? { return when (val raw = rawMember(member)) { is String -> raw - is Int64 -> raw - is Byte -> Int64(raw.toInt()) - is Short -> Int64(raw.toInt()) - is Int -> Int64(raw) - is Long -> Int64(raw) + is Byte -> raw.toLong() + is Short -> raw.toLong() + is Int -> raw.toLong() + is Long -> raw is Float -> raw.toDouble() is Double -> raw is ByteArray -> raw diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TupleCache.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TupleCache.kt index c440dd0d5..8a363c410 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TupleCache.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TupleCache.kt @@ -5,7 +5,6 @@ package naksha.model import naksha.base.AtomicBool import naksha.base.AtomicInt64 import naksha.base.AtomicRef -import naksha.base.Int64 import naksha.base.TupleNumber import naksha.base.fn.Fn1 import naksha.jbon.IDictReader @@ -118,7 +117,7 @@ class TupleCache internal constructor() { * @see [load] */ operator fun get(tupleNumber: TupleNumber): Tuple? { - val ZERO = Int64(0) + val ZERO = 0L return forEachCache { if (it.latencyInMicros == ZERO) it[tupleNumber] else null } } @@ -140,7 +139,7 @@ class TupleCache internal constructor() { tupleNumbers: TupleNumberBinaryArray, from:Int = 0, to:Int = tupleNumbers.size, - maxMicros: Int64? = null, + maxMicros: Long? = null, loadFromStorage: Boolean? = null ): List = load(tupleNumbers.toFeatureTupleList(from, to), maxMicros = maxMicros, loadFromStorage = loadFromStorage).toTupleList() @@ -184,7 +183,7 @@ class TupleCache internal constructor() { featureTuples: LIST, from:Int = 0, to:Int = featureTuples.size, - maxMicros: Int64? = null, + maxMicros: Long? = null, loadFromStorage: Boolean? = null, acceptFeature: Boolean = false ): LIST { @@ -219,7 +218,7 @@ class TupleCache internal constructor() { * @since 3.0 */ fun store(tuple: Tuple) { - forEachCache { if (it.latencyInMicros eq 0) it.put(tuple) } + forEachCache { if (it.latencyInMicros == 0L) it.put(tuple) } } /** @@ -231,7 +230,7 @@ class TupleCache internal constructor() { @JsName("storeAll") fun store(vararg tuples: Tuple) { forEachCache { - if (it.latencyInMicros eq 0) { + if (it.latencyInMicros == 0L) { for (tuple in tuples) { it.put(tuple) } @@ -251,7 +250,7 @@ class TupleCache internal constructor() { @JsName("storeList") fun store(tuples: List) { forEachCache { - if (it.latencyInMicros eq 0) { + if (it.latencyInMicros == 0L) { for (tuple in tuples) { if (tuple != null) { it.put(tuple) @@ -270,7 +269,7 @@ class TupleCache internal constructor() { */ fun storeFeatureTuples(featureTuples: List) { forEachCache { - if (it.latencyInMicros eq 0) { + if (it.latencyInMicros == 0L) { for (f in featureTuples) { val tuple = f?.tuple ?: continue it.put(tuple) @@ -308,7 +307,7 @@ class TupleCache internal constructor() { * @return the [dictionary reader][IDictReader], if any is available. */ @JsName("getDictReaderForStorageId") - fun getDictReader(storageNumber: Int64): IDictReader? + fun getDictReader(storageNumber: Long): IDictReader? = forEachCache { it.getDictReader(storageNumber) } /** @@ -348,4 +347,4 @@ class TupleCache internal constructor() { fun clear(storage: IStorage) { forEachCache { it.clear(storage) } } -} \ No newline at end of file +} diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TupleHeapCache.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TupleHeapCache.kt index 415cf6a83..29a0d1639 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TupleHeapCache.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TupleHeapCache.kt @@ -2,7 +2,6 @@ package naksha.model -import naksha.base.Int64 import naksha.base.TupleNumber import naksha.jbon.IDictReader import naksha.model.request.FeatureTuple @@ -29,14 +28,14 @@ import naksha.model.request.FeatureTuple expect class TupleHeapCache: ITupleCache { // ITupleCache implementation - override val latencyInMicros: Int64 + override val latencyInMicros: Long override operator fun get(tupleNumber: TupleNumber): Tuple? override fun load(featureTuples: List, from:Int, to:Int, acceptFeature: Boolean): Int override fun put(tuple: Tuple) override fun store(tuples: List) override fun onStorageAdd(storage: IStorage) override fun onStorageRemove(storage: IStorage) - override fun getDictReader(storageNumber: Int64): IDictReader? + override fun getDictReader(storageNumber: Long): IDictReader? override fun clear() override fun clear(storage: IStorage) override fun gc() @@ -49,4 +48,4 @@ expect class TupleHeapCache: ITupleCache { */ fun getInstance(): TupleHeapCache } -} \ No newline at end of file +} diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TupleNumberBinaryArray.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TupleNumberBinaryArray.kt index b8a944d65..638e0f7f1 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TupleNumberBinaryArray.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TupleNumberBinaryArray.kt @@ -2,7 +2,6 @@ package naksha.model -import naksha.base.Int64 import naksha.base.Platform import naksha.base.PlatformDataView import naksha.base.PlatformDataViewApi.PlatformDataViewApiCompanion.dataview_get_byte_array @@ -63,10 +62,10 @@ data class TupleNumberBinaryArray( private val length: Int = BinaryUtil.getLength(view) private val contentOffset: Int - private val sharedStorageNumber: Int64? + private val sharedStorageNumber: Long? private val sharedMapNumber: Int? private val sharedCollectionNumber: Int? - private val sharedFeatureNumber: Int64? + private val sharedFeatureNumber: Long? private val entrySize: Int private val dataOffset: Int private val storageNumberOffset: Int @@ -234,7 +233,7 @@ data class TupleNumberBinaryArray( * @return the storage-number. * @since 3.0 */ - fun getStorageNumber(index: Int): Int64 { + fun getStorageNumber(index: Int): Long { val offset = offset(index) if (offset < 0 || offset > last) throw IndexOutOfBoundsException() return sharedStorageNumber ?: dataview_get_int64(view, offset + storageNumberOffset) @@ -270,7 +269,7 @@ data class TupleNumberBinaryArray( * @return the feature-number. * @since 3.0 */ - fun getFeatureNumber(index: Int): Int64 { + fun getFeatureNumber(index: Int): Long { val offset = offset(index) if (offset < 0 || offset > last) throw IndexOutOfBoundsException() return sharedFeatureNumber ?: dataview_get_int64(view, offset + featureNumberOffset) @@ -290,7 +289,7 @@ data class TupleNumberBinaryArray( * @return the transaction-number. * @since 3.0 */ - fun getTxn(index: Int): Int64 { + fun getTxn(index: Int): Long { val offset = offset(index) if (offset < 0 || offset > last) throw IndexOutOfBoundsException() return dataview_get_int64(view, offset + txnOffset) @@ -439,4 +438,4 @@ data class TupleNumberBinaryArray( fun fromByteArray(bytes: ByteArray, from:Int = 0, to:Int = bytes.size) = TupleNumberBinaryArray(Platform.newDataView(bytes, from, to - from)) } -} \ No newline at end of file +} diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TupleNumberList.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TupleNumberList.kt index ed0948977..ce9ea3f31 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TupleNumberList.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TupleNumberList.kt @@ -2,7 +2,6 @@ package naksha.model -import naksha.base.Int64 import naksha.base.ListProxy import naksha.base.Platform import naksha.base.PlatformDataViewApi.PlatformDataViewApiCompanion.dataview_set_int32 @@ -68,10 +67,10 @@ class TupleNumberList : ListProxy(TupleNumber::class) { // if the tuple-numbers share storage-, map-, collection-, and/or feature-number // Note, this code is not thread safe, no other thread must modify the list while we iterate it. var variant: TupleNumberVariant? = null - var storageNumber: Int64? = null + var storageNumber: Long? = null var mapNumber: Int? = -1 var collectionNumber: Int? = -1 - var featureNumber: Int64? = null + var featureNumber: Long? = null for (tupleNumber in this) { if (tupleNumber == null) { length-- @@ -203,4 +202,4 @@ class TupleNumberList : ListProxy(TupleNumber::class) { return rs } } -} \ No newline at end of file +} diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/XyzNs.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/XyzNs.kt index fbff3e03a..154941d2f 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/XyzNs.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/XyzNs.kt @@ -198,7 +198,7 @@ class XyzNs : AnyObject() { private val _STRING_NULL = NullableProperty(String::class, autoRemove = true) private val _INT_0 = NotNullProperty(Int::class) { _, _ -> 0 } private val _INT_NULL = NullableProperty(Int::class, autoRemove = true) - private val _UPDATED_AT = NotNullProperty(Int64::class) { _, _ -> Platform.currentMillis() } + private val _UPDATED_AT = NotNullProperty(Long::class) { _, _ -> Platform.currentMillis() } private val _DOUBLE_NULL = NullableProperty(Double::class, autoRemove = true) private val _TAGS = NotNullProperty(TagList::class) { _, _ -> TagList() } private var AS_IS: CharArray = CharArray(128 - 32) { (it + 32).toChar() } @@ -457,10 +457,10 @@ class XyzNs : AnyObject() { * This field is populated only by **Naksha**. Any values provided by the user will be overwritten. * @since 1.0 */ - val createdAt: Int64 + val createdAt: Long get() { val raw = getRaw("createdAt") - if (raw is Int64) return raw + if (raw is Long) return raw return updatedAt } @@ -527,7 +527,7 @@ class XyzNs : AnyObject() { get() { // Downward compatibility hack. val raw = getRaw("version") - if (raw is Int64 && raw >= Version.MIN_AUTO) return Version(raw) + if (raw is Long && raw >= Version.MIN_AUTO.number) return Version(raw) val version = guid?.tupleNumber?.version return if (version != null) Version(version) else null } @@ -536,7 +536,7 @@ class XyzNs : AnyObject() { * The transaction-number of the feature, basically the same as [version], just as 64-bit integer. * @since 2.0 */ - val txn: Int64? + val txn: Long? get() = guid?.tupleNumber?.version /** @@ -590,10 +590,10 @@ class XyzNs : AnyObject() { * This field is populated only by **Naksha**. Any values provided by the user will be overwritten. * @since 3.0 */ - val authorTs: Int64 + val authorTs: Long get() { val raw = getRaw("authorTs") - if (raw is Int64) return raw + if (raw is Long) return raw return updatedAt } @@ -774,4 +774,4 @@ class XyzNs : AnyObject() { this.tags.addAndNormalizeTags(*tags) return this } -} \ No newline at end of file +} diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/mom/MomDeltaNs.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/mom/MomDeltaNs.kt index d52d6bc9b..f10b4f1c0 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/mom/MomDeltaNs.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/mom/MomDeltaNs.kt @@ -2,7 +2,6 @@ package naksha.model.mom -import naksha.base.Int64 import naksha.base.NotNullProperty import naksha.base.NullableProperty import naksha.base.AnyObject @@ -15,7 +14,7 @@ class MomDeltaNs : AnyObject() { private val STRING_NULL = NullableProperty(String::class) private val CHANGE_STATE = NotNullProperty(String::class) { _, _ -> MomChangeState.CREATED.text } private val REVIEW_STATE = NotNullProperty(String::class) { _, _ -> MomReviewState.UNPUBLISHED.text } - private val INT64 = NotNullProperty(Int64::class) { _, _ -> Int64(0) } + private val INT64 = NotNullProperty(Long::class) { _, _ -> 0L } } /** @@ -41,13 +40,13 @@ class MomDeltaNs : AnyObject() { * whatever value he wants; normal users may not explicitly set this property, therefore for them the value is kept as it is, when not * existing, it is set 0 for normal users. */ - var potentialValue: Int64 by INT64 + var potentialValue: Long by INT64 /** * The priority category assigned to this edit. A value between 0 (no priority, no SLA) and 9. It is never valid to decrease the value * (see CMECMSSUP-1945)! */ - var priorityCategory: Int64 by INT64 + var priorityCategory: Long by INT64 /** * The UNIX epoch timestamp in milliseconds of the time until when the edit must be taken care of. This property is only set automatically @@ -71,4 +70,4 @@ class MomDeltaNs : AnyObject() { fun setReviewStateEnum(enumValue: MomReviewState) { reviewState = enumValue.text } -} \ No newline at end of file +} diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/Member.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/Member.kt index 3c1362ecd..1a5601d4e 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/Member.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/Member.kt @@ -3,7 +3,6 @@ package naksha.model.objects import naksha.base.AnyObject -import naksha.base.Int64 import naksha.base.ListProxy import naksha.base.MapProxy import naksha.base.NotNullEnum @@ -277,7 +276,6 @@ open class Member() : AnyObject(), Comparator { fun readLong(feature: MapProxy<*,*>): Long? { val raw = feature.getPath(path) if (raw is Long) return raw - if (raw is Int64) return raw.toLong() if (raw is Number) return raw.toLong() return null } @@ -392,7 +390,6 @@ open class Member() : AnyObject(), Comparator { @JsName("getInt64FromTuple") fun readLong(tuple: Tuple): Long? { val raw = tuple.getMember(this) - if (raw is Int64) return raw.toLong() if (raw is Long) return raw if (raw is Number) return raw.toLong() return null diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/MemberType.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/MemberType.kt index fd63b78b0..21f5a797f 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/MemberType.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/MemberType.kt @@ -2,7 +2,6 @@ package naksha.model.objects -import naksha.base.Int64 import naksha.base.JsEnum import naksha.geo.SpGeometry import naksha.base.NakshaError.NakshaErrorCompanion.INITIALIZATION_FAILED @@ -246,7 +245,7 @@ class MemberType : JsEnum() { INT8 -> value is Byte INT16 -> value is Byte || value is Short INT32 -> value is Byte || value is Short || value is Int - INT64 -> value is Byte || value is Short || value is Int || value is Long || value is Int64 + INT64 -> value is Byte || value is Short || value is Int || value is Long FLOAT32 -> value is Float FLOAT64 -> value is Float || value is Double STRING -> value is String @@ -268,12 +267,12 @@ class MemberType : JsEnum() { */ @JvmOverloads fun convert(value: Any?, normalize: Boolean = true): Any? = when (this) { - INT8 -> if (value is Number) value.toByte() else if (value is Int64) value.toByte() else null - INT16 -> if (value is Number) value.toShort() else if (value is Int64) value.toShort() else null - INT32 -> if (value is Number) value.toInt() else if (value is Int64) value.toInt() else null - INT64 -> if (value is Number) value.toLong() else if (value is Int64) value.toLong() else null - FLOAT32 -> if (value is Number) value.toFloat() else if (value is Int64) value.toFloat() else null - FLOAT64 -> if (value is Number) value.toDouble() else if (value is Int64) value.toDouble() else null + INT8 -> if (value is Number) value.toByte() else null + INT16 -> if (value is Number) value.toShort() else null + INT32 -> if (value is Number) value.toInt() else null + INT64 -> if (value is Number) value.toLong() else null + FLOAT32 -> if (value is Number) value.toFloat() else null + FLOAT64 -> if (value is Number) value.toDouble() else null STRING -> value as? String ?: if (value is Char || value is CharSequence) value.toString() else null BYTE_ARRAY -> value as? ByteArray TUPLE_NUMBER -> value as? TupleNumber ?: diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/NakshaCatalog.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/NakshaCatalog.kt index 690ffc534..299e65b6b 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/NakshaCatalog.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/NakshaCatalog.kt @@ -2,7 +2,6 @@ package naksha.model.objects -import naksha.base.Int64 import naksha.base.NullableProperty import naksha.geo.SpBoundingBox import naksha.geo.SpGeometry @@ -70,7 +69,7 @@ open class NakshaCatalog() : NakshaFeature() { * @since 3.0 * @throws NakshaException with error [ILLEGAL_STATE], when the collection does not have a valid [tupleNumber]. */ - val databaseNumber: Int64 + val databaseNumber: Long get() = tupleNumber?.databaseNumber ?: throw NakshaException(ILLEGAL_STATE, "The collection has no tuple-number") /** @@ -102,4 +101,4 @@ open class NakshaCatalog() : NakshaFeature() { */ val catalogNumber: Int get() = Naksha.catalogNumber(id) -} \ No newline at end of file +} diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/NakshaCollection.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/NakshaCollection.kt index c321bf146..9dd3ab440 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/NakshaCollection.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/NakshaCollection.kt @@ -80,7 +80,7 @@ open class NakshaCollection() : NakshaFeature() { * @since 3.0 * @throws NakshaException with error [ILLEGAL_STATE], when the collection does not have a valid [tupleNumber]. */ - val databaseNumber: Int64 + val databaseNumber: Long get() = tupleNumber?.databaseNumber ?: throw NakshaException(ILLEGAL_STATE, "The collection has no tuple-number") /** @@ -541,7 +541,7 @@ open class NakshaCollection() : NakshaFeature() { /** * @see [maxAge] */ - open fun withMaxAge(value: Int64): NakshaCollection { + open fun withMaxAge(value: Long): NakshaCollection { this.maxAge = value return this } @@ -564,13 +564,13 @@ open class NakshaCollection() : NakshaFeature() { * The estimated amount of features stored within a collection, read-only property only set by the storage. * @since 3.0 */ - val estimatedFeatureCount: Int64 by _ESTIMATED_FEATURE_COUNT + val estimatedFeatureCount: Long by _ESTIMATED_FEATURE_COUNT /** * The estimated amount of deleted features within a collection, read-only property only set by the storage. * @since 3.0 */ - val estimatedDeletedFeatures: Int64 by _ESTIMATED_DELETED_FEATURES + val estimatedDeletedFeatures: Long by _ESTIMATED_DELETED_FEATURES companion object NakshaCollection_C { /** @@ -687,7 +687,7 @@ open class NakshaCollection() : NakshaFeature() { */ @JvmStatic @JsStatic - val UNKNOWN = Int64(-1) + val UNKNOWN = -1L private val DATABASE_ID = NullableProperty(String::class) private val CATALOG_ID = NullableProperty(String::class) @@ -697,10 +697,10 @@ open class NakshaCollection() : NakshaFeature() { private val PROTECTION_CLASS = NullableProperty(String::class) private val MEMBERS = NullableProperty(MemberList::class) private val INDICES = NullableProperty(IndexList::class) - private val MAX_AGE = NotNullProperty(Int64::class) { _, _ -> Int64(-1) } + private val MAX_AGE = NotNullProperty(Long::class) { _, _ -> -1L } private val QUAD_PARTITION_SIZE = NotNullProperty(Int::class) { _, _ -> 10_485_760 } - private val _ESTIMATED_FEATURE_COUNT = NotNullProperty(Int64::class) { _, _ -> UNKNOWN } - private val _ESTIMATED_DELETED_FEATURES = NotNullProperty(Int64::class) { _, _ -> UNKNOWN } + private val _ESTIMATED_FEATURE_COUNT = NotNullProperty(Long::class) { _, _ -> UNKNOWN } + private val _ESTIMATED_DELETED_FEATURES = NotNullProperty(Long::class) { _, _ -> UNKNOWN } private val STORE_HISTORY = NotNullEnum(StoreMode::class) { self, _ -> // For downward compatibility with Naksha version 2 val old = self.getRaw("disableHistory") diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/NakshaStorage.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/NakshaStorage.kt index 4c2712d55..de8b56584 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/NakshaStorage.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/NakshaStorage.kt @@ -52,7 +52,7 @@ open class NakshaStorage() : NakshaFeature() { private val HARDCAP = NotNullProperty(Int::class) { _, _ -> 0 } private val CREATE = NotNullProperty(Boolean::class) { _, _ -> false } private val UPGRADE = NotNullProperty(Boolean::class) { _, _ -> false } - //private val DB_NUMBER = NotNullProperty(Int64::class) { self, _ -> Naksha.featureNumber(self.id) } + //private val DB_NUMBER = NotNullProperty(Long::class) { self, _ -> Naksha.featureNumber(self.id) } /** * Helper class to parse a JSON configuration into a [NakshaStorage]. @@ -167,7 +167,7 @@ open class NakshaStorage() : NakshaFeature() { * The database-number to which this storage is hard-wired _(until we support multi-databases per storage)_. * @since 3.0 */ - val databaseNumber: Int64 + val databaseNumber: Long get() { // TODO: We need to allow a custom database number, actually we need to decouple the storage from the database. // However, this is a much larger architectural change, so for now, the storage and the database are hard-wired the same! @@ -202,4 +202,4 @@ open class NakshaStorage() : NakshaFeature() { * @since 3.0 */ open fun configEquals(other: NakshaStorage) = this == other -} \ No newline at end of file +} diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/NakshaSubscriptionState.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/NakshaSubscriptionState.kt index 01ac34e1a..51d97b34c 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/NakshaSubscriptionState.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/NakshaSubscriptionState.kt @@ -20,7 +20,7 @@ open class NakshaSubscriptionState() : AnyObject() { companion object { private val ID = NotNullProperty(String::class) { _, _ -> PlatformUtil.randomString() } private val INT_0 = NotNullProperty(Int::class) { _, _ -> 0 } - private val INT64_0 = NotNullProperty(Int64::class) { _, _ -> Int64(0) } + private val INT64_0 = NotNullProperty(Long::class) { _, _ -> 0L } private val ERROR_NULL = NullableProperty(NakshaError::class) private val ANY_OBJECT = NotNullProperty(AnyObject::class) } diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/NakshaTx.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/NakshaTx.kt index 0a1e3e8c2..00e03c59b 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/NakshaTx.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/NakshaTx.kt @@ -33,8 +33,8 @@ open class NakshaTx : NakshaFeature() { companion object NakshaTransaction_C { private val INT_0 = NotNullProperty(Int::class, init = { _, _ -> 0 }) private val MAPS = NotNullProperty(NakshaTxMapById::class) - private val INT64_NULL = NotNullProperty(Int64::class) - private val TIME = NotNullProperty(Int64::class) { _, _ -> Platform.currentMillis() } + private val INT64_NULL = NotNullProperty(Long::class) + private val TIME = NotNullProperty(Long::class) { _, _ -> Platform.currentMillis() } } /** @@ -44,7 +44,7 @@ open class NakshaTx : NakshaFeature() { * @since 3.0 */ @JvmOverloads - fun setEpoch(epoch: Timestamp, seq: Int64 = Int64(0)): NakshaTx { + fun setEpoch(epoch: Timestamp, seq: Long = 0L): NakshaTx { val version = Version.auto(epoch.year, epoch.month, epoch.day, seq, Action.VERSION) setRaw("id", version.toString()) setRaw("time", epoch.ts) @@ -81,8 +81,8 @@ open class NakshaTx : NakshaFeature() { * @since 3.0 */ @JvmOverloads - fun setNow(seq: Int64? = null): NakshaTx { - setEpoch(Timestamp.now(), seq ?: Int64(0)) + fun setNow(seq: Long? = null): NakshaTx { + setEpoch(Timestamp.now(), seq ?: 0L) return this } @@ -95,7 +95,7 @@ open class NakshaTx : NakshaFeature() { override var id: String get() = getAs("id", String::class) ?: throw illegalState("The property 'id' must be a valid string") set(value) { - val txn = Int64(value.toLong(10)) + val txn = value.toLong(10) setVersion(Version(txn)) } @@ -109,7 +109,7 @@ open class NakshaTx : NakshaFeature() { val time by TIME private var _epoch: Timestamp? = null - private var _epochTime: Int64? = null + private var _epochTime: Long? = null /** * The [time] as [Timestamp]. @@ -120,7 +120,7 @@ open class NakshaTx : NakshaFeature() { val time = this.time var _epoch = this._epoch val _epochTime = this._epochTime - if (_epoch != null && _epochTime === time) return _epoch + if (_epoch != null && _epochTime == time) return _epoch _epoch = Timestamp.fromMillis(time) this._epochTime = time this._epoch = _epoch @@ -153,7 +153,7 @@ open class NakshaTx : NakshaFeature() { * The transaction number, basically just `version.txn`. * @since 3.0 */ - val txn: Int64 + val txn: Long get() = version.number /** @@ -209,4 +209,4 @@ open class NakshaTx : NakshaFeature() { maps[id] = mapInfo return mapInfo } -} \ No newline at end of file +} diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/XyzProcessors.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/XyzProcessors.kt index 733d61784..1643a5184 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/XyzProcessors.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/objects/XyzProcessors.kt @@ -1,7 +1,6 @@ package naksha.model.objects import naksha.base.Fnv1a32 -import naksha.base.Int64 import naksha.base.Platform import naksha.geo.HereTile import naksha.base.Action @@ -40,7 +39,6 @@ class XyzProcessors private constructor() { val xyzCreatedAt = IMemberProcessor { _, collection, feature, _, value -> when (value) { is Long -> value - is Int64 -> value.toLong() is Number -> value.toLong() else -> { val action = collection.useMember(StandardMembers.Tn).readTupleNumber(feature)?.action @@ -77,7 +75,6 @@ class XyzProcessors private constructor() { @JvmStatic val xyzAuthorTimestamp = IMemberProcessor { session, _, _, _, value -> if (session.options.author != null) Platform.currentMillis().toLong() - else if (value is Int64) value.toLong() else value as? Long ?: if (value is Number) value.toLong() else null } diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/ReadFeatures.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/ReadFeatures.kt index 39704c851..af7ef811e 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/ReadFeatures.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/ReadFeatures.kt @@ -2,7 +2,6 @@ package naksha.model.request -import naksha.base.Int64 import naksha.base.NotNullProperty import naksha.base.NullableProperty import naksha.base.StringList @@ -151,7 +150,7 @@ open class ReadFeatures : ReadRequest() { var versions: Int get() { val raw = getRaw("versions") - if (raw is Int64) return max(1, raw.toInt()) + if (raw is Long) return max(1, raw.toInt()) if (raw is Number) return max(1, raw.toInt()) return 1 } @@ -166,12 +165,12 @@ open class ReadFeatures : ReadRequest() { * If the underlying JSON map contains a values that is not a number or invalid, the default value `null` will be used. * @since 3.0 */ - var minVersion: Int64? + var minVersion: Long? get() { val raw = getRaw("minVersion") - if (raw is Int64) return if (raw < Version.MIN.number || raw > Version.HEAD.number) null else raw + if (raw is Long) return if (raw < Version.MIN.number || raw > Version.HEAD.number) null else raw if (raw is Number) { - val value = Int64(raw.toLong()) + val value = raw.toLong() return if (value < Version.MIN.number || value > Version.HEAD.number) null else value } return null @@ -187,7 +186,7 @@ open class ReadFeatures : ReadRequest() { * @see minVersion */ @JsName("withMinVersionInt64") - fun withMinVersion(minVersion: Int64?): ReadFeatures { + fun withMinVersion(minVersion: Long?): ReadFeatures { this.minVersion = minVersion return this } @@ -201,15 +200,6 @@ open class ReadFeatures : ReadRequest() { return this } - /** - * @see minVersion - */ - @JsName("withMinVersionLong") - fun withMinVersion(minVersion: Long?): ReadFeatures { - this.minVersion = if (minVersion != null) Int64(minVersion) else null - return this - } - /** * Limit the read to states at or before the given maximum version, `null` if no limit _(read up to [HEAD][Version.VersionCompanion.HEAD] aka up until latest state)_. * @@ -218,11 +208,11 @@ open class ReadFeatures : ReadRequest() { * If the underlying JSON map contains a values that is not a number or invalid, the default value `null` will be used. * @since 3.0 */ - var version: Int64? + var version: Long? get() { val raw = getRaw("version") - if (raw is Int64) return raw - if (raw is Number) return Int64(raw.toLong()) + if (raw is Long) return raw + if (raw is Number) return raw.toLong() return null } set(value) { @@ -233,7 +223,7 @@ open class ReadFeatures : ReadRequest() { * @see version */ @JsName("withVersionInt64") - fun withVersion(version: Int64?): ReadFeatures { + fun withVersion(version: Long?): ReadFeatures { this.version = version return this } @@ -247,15 +237,6 @@ open class ReadFeatures : ReadRequest() { return this } - /** - * @see version - */ - @JsName("withVersionLong") - fun withVersion(version: Long?): ReadFeatures { - this.version = if (version != null) Int64(version) else null - return this - } - /** * Order the result-set like given; this is an expensive operation and should be avoided. @@ -329,4 +310,4 @@ open class ReadFeatures : ReadRequest() { && featureIds.isEmpty() && guids.isEmpty() && query.hasNoConditions() -} \ No newline at end of file +} diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/Write.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/Write.kt index 645ef2b70..e6ba9eaa0 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/Write.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/Write.kt @@ -183,7 +183,7 @@ open class Write : AnyObject() { return this } - private var versionRaw: Int64? = null + private var versionRaw: Long? = null private var versionValue: Version? = null /** @@ -199,11 +199,11 @@ open class Write : AnyObject() { get() { var raw = getRaw("version") if (raw is Double) { - raw = raw.toInt64() + raw = raw.toLong() setRaw("version", raw) } - if (raw is Int64) { - if (raw === versionRaw) return versionValue + if (raw is Long) { + if (raw == versionRaw) return versionValue versionRaw = raw versionValue = Version(raw) return versionValue @@ -334,7 +334,7 @@ open class Write : AnyObject() { } private var featureNumberId: String? = null - private var featureNumberValue: Int64? = null + private var featureNumberValue: Long? = null /** * The **feature-number** to operate upon. @@ -345,15 +345,15 @@ open class Write : AnyObject() { * @since 3.0 */ @Suppress("SENSELESS_COMPARISON") - var featureNumber: Int64 + var featureNumber: Long get() { val raw = getRaw("featureNumber") - if (raw is Int64) return raw + if (raw is Long) return raw // TODO: This is a hack, we need to change this. // Without the collection, we normally do not know where the tuple-number is located within a feature. val feature = this.feature - var fn: Int64? = null + var fn: Long? = null if (feature != null) { fn = XyzMembers.XyzTn.readTupleNumber(feature)?.featureNumber if (fn == null) fn = StandardMembers.Tn.readTupleNumber(feature)?.featureNumber @@ -384,7 +384,7 @@ open class Write : AnyObject() { * This method allows to reset the [featureNumber] to `null`, which means "go back to default behavior". * @see [featureNumber] */ - fun withFeatureNumber(value: Int64?): Write { + fun withFeatureNumber(value: Long?): Write { if (value == null) removeRaw("featureNumber") else setRaw("featureNumber", value) return this } @@ -397,7 +397,7 @@ open class Write : AnyObject() { */ @JsName("withFeatureNumber32") fun withFeatureNumber(value: Int?): Write { - val featureNumber = if (value == null) null else value.toInt64() and Naksha.INT64_CLEAR_HIGH32 + val featureNumber = if (value == null) null else value.toLong() and Naksha.INT64_CLEAR_HIGH32 withFeatureNumber(featureNumber) return this } @@ -957,4 +957,4 @@ open class Write : AnyObject() { } // otherwise, arbitrary feature is modified, we allow any identifier. return this } -} \ No newline at end of file +} diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/notification/NotificationAck.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/notification/NotificationAck.kt index bcd90f4da..943b73228 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/notification/NotificationAck.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/notification/NotificationAck.kt @@ -1,7 +1,6 @@ package naksha.model.request.notification import naksha.model.request.Response -import naksha.base.Int64 import naksha.base.MapProxy import kotlin.js.ExperimentalJsExport import kotlin.js.JsExport @@ -14,9 +13,9 @@ import kotlin.js.JsExport @OptIn(ExperimentalJsExport::class) @JsExport class NotificationAck( - val seqNumber: Int64, + val seqNumber: Long, val uid: Int, val handlerStates: MapProxy ) : Response() { override fun resultSize(): Int = 0 -} \ No newline at end of file +} diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/notification/NotificationError.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/notification/NotificationError.kt index db331383b..aa791dd31 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/notification/NotificationError.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/notification/NotificationError.kt @@ -2,7 +2,6 @@ package naksha.model.request.notification import naksha.model.request.ErrorResponse import naksha.base.NakshaError -import naksha.base.Int64 import naksha.base.MapProxy import kotlin.js.ExperimentalJsExport import kotlin.js.JsExport @@ -16,7 +15,7 @@ import kotlin.js.JsExport @JsExport class NotificationError( reason: NakshaError, - val seqNumber: Int64, + val seqNumber: Long, val uid: Int, val handlerStates: MapProxy -) : ErrorResponse(reason) \ No newline at end of file +) : ErrorResponse(reason) diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/notification/TuplesByTxn.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/notification/TuplesByTxn.kt index 9a1ef33e8..c02ee5932 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/notification/TuplesByTxn.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/notification/TuplesByTxn.kt @@ -2,7 +2,6 @@ package naksha.model.request.notification -import naksha.base.Int64 import naksha.base.MapProxy import naksha.base.Version import naksha.model.request.FeatureTuple @@ -13,4 +12,4 @@ import kotlin.js.JsExport * A map where the key is the transaction number (aka [Version]), and the value is a list of [result-rows][FeatureTuple], order by [uid][naksha.model.Metadata.uid]. */ @JsExport -class TuplesByTxn : MapProxy(Int64::class, FeatureTupleList::class) +class TuplesByTxn : MapProxy(Long::class, FeatureTupleList::class) diff --git a/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/AbstractStorageTest.kt b/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/AbstractStorageTest.kt index 99c1defc8..11601d380 100644 --- a/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/AbstractStorageTest.kt +++ b/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/AbstractStorageTest.kt @@ -5,7 +5,6 @@ import kotlinx.datetime.TimeZone import kotlinx.datetime.number import kotlinx.datetime.toLocalDateTime import naksha.base.Action -import naksha.base.Int64 import naksha.base.NakshaError.NakshaErrorCompanion.UNINITIALIZED import naksha.base.NakshaException import naksha.base.TupleNumber @@ -48,8 +47,8 @@ class AbstractStorageTest { fun newVirtualVersionDoesNotRollBackSequenceWithNewerDate() { val previousDay = LocalDateTime(2026, 8, 24, 23, 59, 59) val nextDay = LocalDateTime(2026, 8, 25, 0, 0, 0) - val previousDayVersion = Version.auto(2026, 8, 24, Int64(0), Action.VERSION) - val nextDayVersion = Version.auto(2026, 8, 25, Int64(0), Action.VERSION) + val previousDayVersion = Version.auto(2026, 8, 24, 0L, Action.VERSION) + val nextDayVersion = Version.auto(2026, 8, 25, 0L, Action.VERSION) val storage = TestStorage() var competingVersion: Version? = null @@ -73,7 +72,7 @@ class AbstractStorageTest { val collectionId = "test-collection" val featureId = "test-feature" val storage = TestStorage().apply { initialize(storageId) } - val version = Version.auto(2026, 8, 24, Int64(42), Action.VERSION).number + val version = Version.auto(2026, 8, 24, 42L, Action.VERSION).number for (action in listOf(Action.CREATE, Action.UPDATE, Action.DELETE, Action.VERSION)) { val tupleNumber = storage.newTupleNumber(catalogId, collectionId, featureId, version, action) @@ -90,7 +89,7 @@ class AbstractStorageTest { @Test fun newVirtualTupleNumberRequiresInitializedStorage() { val exception = assertFailsWith { - TestStorage().newTupleNumber("catalog", "collection", "feature", Int64(3), Action.VERSION) + TestStorage().newTupleNumber("catalog", "collection", "feature", 3L, Action.VERSION) } assertEquals(UNINITIALIZED, exception.error.code) @@ -133,11 +132,11 @@ class AbstractStorageTest { invokeInitStorage(NakshaStorage(storageId, "TestStorage"), create = null, upgrade = null) } - fun resetNextVirtualVersion(version: Int64) { + fun resetNextVirtualVersion(version: Long) { nextVirtualVersion.set(version) } - fun peekNextVirtualVersion(): Int64 = nextVirtualVersion.get() + fun peekNextVirtualVersion(): Long = nextVirtualVersion.get() fun fakeVirtualVersionTime(times: List, afterFirstAcquire: () -> Unit) { fakeTimes = times.toMutableList() @@ -149,14 +148,14 @@ class AbstractStorageTest { override fun newVirtualVersion(): Version { val times = fakeTimes ?: return super.newVirtualVersion() while (true) { - val version = Version(nextVirtualVersion.getAndAdd(Int64(4))) + val version = Version(nextVirtualVersion.getAndAdd(4L)) afterAcquire?.let { hook -> afterAcquire = null hook() } val now = times.removeAt(0) if (version.isBehind(now.year, now.month.number, now.day)) { - val newVersion = Version.auto(now.year, now.month.number, now.day, Int64(0), Action.VERSION) + val newVersion = Version.auto(now.year, now.month.number, now.day, 0L, Action.VERSION) if (nextVirtualVersion.compareAndSet(version.number + 4, newVersion.number + 4)) { return newVersion } @@ -170,7 +169,7 @@ class AbstractStorageTest { catalogId: String, collectionId: String, featureId: String, - version: Int64, + version: Long, action: Action, ): TupleNumber = newVirtualTupleNumber(catalogId, collectionId, featureId, version, action) diff --git a/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/GuidTest.kt b/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/GuidTest.kt index 7181de9a0..73b0477ff 100644 --- a/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/GuidTest.kt +++ b/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/GuidTest.kt @@ -1,6 +1,5 @@ package naksha.model -import naksha.base.Int64 import kotlin.test.Test import kotlin.test.assertEquals @@ -15,7 +14,7 @@ class GuidTest { // featureId = "Feature1", // luid = RowId( // uid = 11, -// version = Version.of(2001, 11, 26, Int64(3)) +// version = Version.of(2001, 11, 26, 3L) // ) // ) // @@ -26,7 +25,7 @@ class GuidTest { // @Test // fun shouldTransformTxtToGuid() { // // given -// val txn = Version.of(2001, 11, 26, Int64(3)) +// val txn = Version.of(2001, 11, 26, 3L) // // // when // val guid = txn.toGuid("naksha", "foo", "foo1") @@ -38,4 +37,4 @@ class GuidTest { // assertEquals(26, txn.day()) // assertEquals(3, txn.seq().toInt()) // } -} \ No newline at end of file +} diff --git a/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/MemberTest.kt b/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/MemberTest.kt index 40376a4d5..d79bf6a7c 100644 --- a/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/MemberTest.kt +++ b/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/MemberTest.kt @@ -93,7 +93,6 @@ class MemberTest { assertNotNull(MemberType.BYTE_ARRAY) // Virtual / jsonb. assertNotNull(MemberType.TAG_MAP) - assertNotNull(MemberType.TAG_MAP_FROM_TAG_LIST) assertNotNull(MemberType.TAG_LIST) } diff --git a/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/NakshaCollectionProxyTest.kt b/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/NakshaCollectionProxyTest.kt index 22fd44d2f..e7c85b750 100644 --- a/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/NakshaCollectionProxyTest.kt +++ b/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/NakshaCollectionProxyTest.kt @@ -1,6 +1,5 @@ package naksha.model -import naksha.base.Int64 import naksha.model.objects.NakshaCollection import naksha.model.objects.StoreMode import kotlin.test.Test @@ -18,7 +17,7 @@ class NakshaCollectionProxyTest { storeDeleted = StoreMode.SUSPEND, storeHistory = StoreMode.OFF ) - collection.maxAge = Int64(42) + collection.maxAge = 42L // expect assertEquals("ID", collection.id) @@ -27,4 +26,4 @@ class NakshaCollectionProxyTest { assertEquals(StoreMode.SUSPEND, collection.storeDeleted) assertEquals(StoreMode.OFF, collection.storeHistory) } -} \ No newline at end of file +} diff --git a/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/NakshaTest.kt b/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/NakshaTest.kt index a1c68a67f..fbb19305c 100644 --- a/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/NakshaTest.kt +++ b/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/NakshaTest.kt @@ -1,7 +1,6 @@ package naksha.model import naksha.base.Binary -import naksha.base.Int64 import naksha.base.Platform import naksha.base.PlatformUtil.PlatformUtilCompanion.randomString import naksha.model.Naksha.NakshaCompanion.INT64_SIGN_BIT @@ -36,24 +35,24 @@ class NakshaTest { @Test fun shouldConvertNumericIdsToFeatureNumber() { // expect - assertEquals(Int64(0L), Naksha.featureNumber("0")) - assertEquals(Int64(1L), Naksha.featureNumber("1")) - assertEquals(Int64(5000L), Naksha.featureNumber("5000")) - assertEquals(Int64(9223372036854775807L), Naksha.featureNumber("9223372036854775807")) + assertEquals(0L, Naksha.featureNumber("0")) + assertEquals(1L, Naksha.featureNumber("1")) + assertEquals(5000L, Naksha.featureNumber("5000")) + assertEquals(9223372036854775807L, Naksha.featureNumber("9223372036854775807")) } @Test fun shouldNotConvertNegativeNumericIdsToFeatureNumber() { // expect - assertNotEquals(Int64(-1L), Naksha.featureNumber("-1")) - assertNotEquals(Int64(-100L), Naksha.featureNumber("-100")) + assertNotEquals(-1L, Naksha.featureNumber("-1")) + assertNotEquals(-100L, Naksha.featureNumber("-100")) } @Test fun shouldNotConvertNumericIdsWithLeadingZeroToFeatureNumber() { // expect - assertNotEquals(Int64(0L), Naksha.featureNumber("00")) - assertNotEquals(Int64(1L), Naksha.featureNumber("01")) + assertNotEquals(0L, Naksha.featureNumber("00")) + assertNotEquals(1L, Naksha.featureNumber("01")) } @Test @@ -91,41 +90,41 @@ class NakshaTest { * A map between a feature-id and its feature-number, partition-number. */ val featureNumbers = mapOf( - Pair("apple", Pair(Int64(-5484511280634489473), 38271)), - Pair("mountain", Pair(Int64(-7643729615383602773), 22955)), - Pair("river", Pair(Int64(-8583638578235004148), 43788)), - Pair("sunshine", Pair(Int64(-4226617501311062128), 44944)), - Pair("thunderstorm", Pair(Int64(-1662902383593395660), 59956)), - Pair("ocean", Pair(Int64(-814082869712769487), 11825)), - Pair("whisper", Pair(Int64(-3749626363697139386), 28998)), - Pair("horizon", Pair(Int64(-7642222644562628650), 61398)), - Pair("galaxy", Pair(Int64(-883295718727625417), 54583)), - Pair("waterfall", Pair(Int64(-7660642750086972487), 64441)), - Pair("adventure", Pair(Int64(-7128644326194761764), 45020)), - Pair("brilliant", Pair(Int64(-5335221019134199366), 63930)), - Pair("cinnamon", Pair(Int64(-2248730746238684729), 45511)), - Pair("discover", Pair(Int64(-6128714515268687570), 10542)), - Pair("elephant", Pair(Int64(-7157438305210013553), 59535)), - Pair("friendship", Pair(Int64(-6290951814662559583), 26785)), - Pair("grateful", Pair(Int64(-700925958107943057), 12143)), - Pair("happiness", Pair(Int64(-4386989945280691918), 33074)), - Pair("inspire", Pair(Int64(-2792765718126701116), 21956)), - Pair("journey", Pair(Int64(-5734938501861003441), 12111)), - Pair("kindness", Pair(Int64(-432081468076469306), 54214)), - Pair("lighthouse", Pair(Int64(-2138142157099628800), 1792)), - Pair("marvelous", Pair(Int64(-4532173556937446518), 11146)), - Pair("nostalgia", Pair(Int64(-8803792262422751274), 38870)), - Pair("optimistic", Pair(Int64(-5230136328746208797), 29155)), - Pair("peaceful", Pair(Int64(-5292427495373678802), 55086)), - Pair("question", Pair(Int64(-5073713729616654471), 20345)), - Pair("remarkable", Pair(Int64(-3533350706736017749), 52907)), - Pair("timeless", Pair(Int64(-8277156549585841745), 20911)), - Pair("universe", Pair(Int64(-1692936746790842146), 37086)), - Pair("victorious", Pair(Int64(-6472092707646497588), 40140)), - Pair("wonderful", Pair(Int64(-284636615007774547), 22701)), - Pair("zephyr", Pair(Int64(-6766911163183497362), 32622)), - Pair("A7l9RsIxWZCp2I6i3wXo", Pair(Int64(-6293233423437375615), 22401)), - Pair("A6ixOLtAZF8IhKez25zY", Pair(Int64(-318328739946057960), 44824)), + Pair("apple", Pair(-5484511280634489473L, 38271)), + Pair("mountain", Pair(-7643729615383602773L, 22955)), + Pair("river", Pair(-8583638578235004148L, 43788)), + Pair("sunshine", Pair(-4226617501311062128L, 44944)), + Pair("thunderstorm", Pair(-1662902383593395660L, 59956)), + Pair("ocean", Pair(-814082869712769487L, 11825)), + Pair("whisper", Pair(-3749626363697139386L, 28998)), + Pair("horizon", Pair(-7642222644562628650L, 61398)), + Pair("galaxy", Pair(-883295718727625417L, 54583)), + Pair("waterfall", Pair(-7660642750086972487L, 64441)), + Pair("adventure", Pair(-7128644326194761764L, 45020)), + Pair("brilliant", Pair(-5335221019134199366L, 63930)), + Pair("cinnamon", Pair(-2248730746238684729L, 45511)), + Pair("discover", Pair(-6128714515268687570L, 10542)), + Pair("elephant", Pair(-7157438305210013553L, 59535)), + Pair("friendship", Pair(-6290951814662559583L, 26785)), + Pair("grateful", Pair(-700925958107943057L, 12143)), + Pair("happiness", Pair(-4386989945280691918L, 33074)), + Pair("inspire", Pair(-2792765718126701116L, 21956)), + Pair("journey", Pair(-5734938501861003441L, 12111)), + Pair("kindness", Pair(-432081468076469306L, 54214)), + Pair("lighthouse", Pair(-2138142157099628800L, 1792)), + Pair("marvelous", Pair(-4532173556937446518L, 11146)), + Pair("nostalgia", Pair(-8803792262422751274L, 38870)), + Pair("optimistic", Pair(-5230136328746208797L, 29155)), + Pair("peaceful", Pair(-5292427495373678802L, 55086)), + Pair("question", Pair(-5073713729616654471L, 20345)), + Pair("remarkable", Pair(-3533350706736017749L, 52907)), + Pair("timeless", Pair(-8277156549585841745L, 20911)), + Pair("universe", Pair(-1692936746790842146L, 37086)), + Pair("victorious", Pair(-6472092707646497588L, 40140)), + Pair("wonderful", Pair(-284636615007774547L, 22701)), + Pair("zephyr", Pair(-6766911163183497362L, 32622)), + Pair("A7l9RsIxWZCp2I6i3wXo", Pair(-6293233423437375615L, 22401)), + Pair("A6ixOLtAZF8IhKez25zY", Pair(-318328739946057960L, 44824)), ) } @@ -134,7 +133,7 @@ class NakshaTest { append(byte.toUByte().toString(16).padStart(2, '0')) } } - private fun printPairIfIncorrect(id: String, fn: Int64, pn: Int) { + private fun printPairIfIncorrect(id: String, fn: Long, pn: Int) { val bytes = Platform.md5(id) // To compare: https://www.md5hashgenerator.com/ val hex = toHex(bytes) @@ -143,7 +142,7 @@ class NakshaTest { val signedLower = lower or INT64_SIGN_BIT val lower16 = signedLower.toInt() and 65535 if (signedLower != fn || lower16 != pn) { - println("Pair(\"$id\", Pair(Int64($signedLower), ${lower16})),") + println("Pair(\"$id\", Pair(${signedLower}L, ${lower16})),") } } private fun generate() { diff --git a/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/TransactionNumberTest.kt b/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/TransactionNumberTest.kt index 0b7559e12..7b9b5f310 100644 --- a/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/TransactionNumberTest.kt +++ b/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/TransactionNumberTest.kt @@ -1,7 +1,6 @@ package naksha.model import naksha.base.Action -import naksha.base.Int64 import naksha.base.Version import kotlin.test.Test import kotlin.test.assertEquals @@ -9,9 +8,9 @@ import kotlin.test.assertEquals class TransactionNumberTest { @Test fun versionFromToString() { - val v1 = Version.auto(2024, 5, 10, Int64(12345), Action.VERSION) + val v1 = Version.auto(2024, 5, 10, 12345L, Action.VERSION) val s = v1.toString() val parsed = Version.fromString(s) assertEquals(v1.number, parsed.number) } -} \ No newline at end of file +} diff --git a/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/TupleNumberTest.kt b/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/TupleNumberTest.kt index 2faac689c..da04cb21d 100644 --- a/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/TupleNumberTest.kt +++ b/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/TupleNumberTest.kt @@ -1,7 +1,6 @@ package naksha.model import naksha.base.Action -import naksha.base.Int64 import naksha.base.TupleNumber import naksha.base.TupleNumberVariant.TupleNumberVariant_C.B64 import naksha.base.TupleNumberVariant.TupleNumberVariant_C.B128 @@ -13,17 +12,17 @@ import kotlin.test.assertEquals class TupleNumberTest { - private val storageNumber = Int64(1L) + private val storageNumber = 1L private val mapNumber = 2 private val collectionNumber = 3 - private val featureNumber = Int64(0x12345678_9ABCDEF0L) + private val featureNumber = 0x12345678_9ABCDEF0L // txn value with lower 2 bits clear so we can OR in the action bits - private val txnBase = Int64(0x0102_0304_0506_0708L and -4L) + private val txnBase = 0x0102_0304_0506_0708L and -4L /** Build a TupleNumber with the given action encoded in the lower 2 bits of txn. * action.intValue is the raw 2-bit value (0=CREATED, 1=UPDATED, 2=DELETED). */ private fun tn(action: Action): TupleNumber { - val txn = txnBase or Int64(action.intValue.toLong()) + val txn = txnBase or action.longValue return TupleNumber(storageNumber, mapNumber, collectionNumber, featureNumber, txn) } diff --git a/here-naksha-lib-model/src/jsMain/kotlin/naksha/model/TupleHeapCache.js.kt b/here-naksha-lib-model/src/jsMain/kotlin/naksha/model/TupleHeapCache.js.kt index ba88d3dd6..21d4b1d57 100644 --- a/here-naksha-lib-model/src/jsMain/kotlin/naksha/model/TupleHeapCache.js.kt +++ b/here-naksha-lib-model/src/jsMain/kotlin/naksha/model/TupleHeapCache.js.kt @@ -2,7 +2,6 @@ package naksha.model -import naksha.base.Int64 import naksha.base.TupleNumber import naksha.jbon.IDictReader import naksha.model.request.FeatureTuple @@ -14,7 +13,7 @@ import naksha.model.request.FeatureTuple * @since 3.0 */ actual class TupleHeapCache : ITupleCache { - actual override val latencyInMicros: Int64 + actual override val latencyInMicros: Long get() = LATENCY_MEMORY actual override fun get(tupleNumber: TupleNumber): Tuple? { @@ -41,7 +40,7 @@ actual class TupleHeapCache : ITupleCache { TODO("Not yet implemented") } - actual override fun getDictReader(storageNumber: Int64): IDictReader? { + actual override fun getDictReader(storageNumber: Long): IDictReader? { TODO("Not yet implemented") } @@ -67,4 +66,4 @@ actual class TupleHeapCache : ITupleCache { TODO("Not yet implemented") } } -} \ No newline at end of file +} diff --git a/here-naksha-lib-model/src/jvmMain/kotlin/naksha/model/TupleHeapCache.jvm.kt b/here-naksha-lib-model/src/jvmMain/kotlin/naksha/model/TupleHeapCache.jvm.kt index 652c846f7..1cfb01fe1 100644 --- a/here-naksha-lib-model/src/jvmMain/kotlin/naksha/model/TupleHeapCache.jvm.kt +++ b/here-naksha-lib-model/src/jvmMain/kotlin/naksha/model/TupleHeapCache.jvm.kt @@ -3,14 +3,13 @@ package naksha.model import naksha.base.AtomicMap -import naksha.base.Int64 import naksha.base.TupleNumber import naksha.base.WeakRef import naksha.jbon.IDictReader import naksha.model.request.FeatureTuple actual class TupleHeapCache : ITupleCache { - actual override val latencyInMicros: Int64 + actual override val latencyInMicros: Long get() = LATENCY_MEMORY // TODO: Review Caffeine, we should use it! @@ -22,7 +21,7 @@ actual class TupleHeapCache : ITupleCache { // Eventually we should use all other available additional memory via weak-references for caching. // All heap references should always be weak-referred to be collectable under memory pressure. // The partial tuples should use only weak-references, they are very unhandy anyway and should be avoided. - private var tuplesByStorage = AtomicMap>>() + private var tuplesByStorage = AtomicMap>>() actual override fun get(tupleNumber: TupleNumber): Tuple? = tuplesByStorage[tupleNumber.databaseNumber]?.get(tupleNumber)?.deref() @@ -68,7 +67,7 @@ actual class TupleHeapCache : ITupleCache { actual override fun onStorageRemove(storage: IStorage) { } - actual override fun getDictReader(storageNumber: Int64): IDictReader? { + actual override fun getDictReader(storageNumber: Long): IDictReader? { // TODO: Implement me! return null } @@ -95,4 +94,4 @@ actual class TupleHeapCache : ITupleCache { */ actual fun getInstance(): TupleHeapCache = theInstance } -} \ No newline at end of file +} diff --git a/here-naksha-lib-model/src/jvmTest/kotlin/naksha/model/PropertyFilterTest.kt b/here-naksha-lib-model/src/jvmTest/kotlin/naksha/model/PropertyFilterTest.kt index 5eae9b846..5af1f68d9 100644 --- a/here-naksha-lib-model/src/jvmTest/kotlin/naksha/model/PropertyFilterTest.kt +++ b/here-naksha-lib-model/src/jvmTest/kotlin/naksha/model/PropertyFilterTest.kt @@ -1,6 +1,5 @@ package naksha.model -import naksha.base.Int64 import naksha.base.Platform import naksha.base.Proxy import naksha.base.TupleNumber @@ -469,7 +468,7 @@ class PropertyFilterTest { val feature = Proxy.box(Platform.fromJSON(featureJson), NakshaFeature::class)!! val encoder = JbEncoder2() val featureBytes = encoder.buildTupleFromMap(feature) - val storageNumber = Int64(1) + val storageNumber = 1L val mapNumber = 0 val collectionNumber = 0 val version = Version(0) @@ -482,7 +481,7 @@ class PropertyFilterTest { ) val members = HeapBook(BookType.MEMBER_BOOK) members.put(XyzTn.name, tupleNumber) - members.put(XyzUpdatedAt.name, Int64(0)) + members.put(XyzUpdatedAt.name, 0L) members.put(XyzId.name, feature.id) members.put(XyzAppId.name, "") members.put(XyzAuthor.name, null) @@ -494,4 +493,4 @@ class PropertyFilterTest { return FeatureTuple(tupleNumber, tuple) } } -} \ No newline at end of file +} diff --git a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/JbNakshaCollectionDecoder.kt b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/JbNakshaCollectionDecoder.kt index 94cc4cf15..89d38f2cc 100644 --- a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/JbNakshaCollectionDecoder.kt +++ b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/JbNakshaCollectionDecoder.kt @@ -2,7 +2,6 @@ package naksha.psql -import naksha.base.Int64 import naksha.base.Platform import naksha.jbon.IDictManager import naksha.jbon.JbFeatureDecoder @@ -27,9 +26,9 @@ class JbNakshaCollectionDecoder(dictManager: IDictManager) : JbFeatureDecoder(di private var _geoIndex: String? = null private var _disableHistory = false private var _autoPurge = false - private var _maxAge: Int64? = null - private var _estimatedFeatureCount: Int64? = null - private var _estimatedDeletedCount: Int64? = null + private var _maxAge: Long? = null + private var _estimatedFeatureCount: Long? = null + private var _estimatedDeletedCount: Long? = null private var _storageClass: String? = null override fun clear(): JbNakshaCollectionDecoder { @@ -67,7 +66,7 @@ class JbNakshaCollectionDecoder(dictManager: IDictManager) : JbFeatureDecoder(di fun geoIndex(): String = _geoIndex ?: "gist" fun disableHistory(): Boolean = _disableHistory fun autoPurge(): Boolean = _autoPurge - fun maxAge(): Int64 = _maxAge ?: Platform.INT64_MAX_VALUE - fun estimatedFeatureCount(): Int64 = _estimatedFeatureCount ?: NakshaCollection.UNKNOWN + fun maxAge(): Long = _maxAge ?: Platform.INT64_MAX_VALUE + fun estimatedFeatureCount(): Long = _estimatedFeatureCount ?: NakshaCollection.UNKNOWN fun storageClass(): String = _storageClass ?: PgStorageClass.Consistent.toString() -} \ No newline at end of file +} diff --git a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgAdminCatalog.kt b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgAdminCatalog.kt index 1f40ec3a7..d226b08bc 100644 --- a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgAdminCatalog.kt +++ b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgAdminCatalog.kt @@ -8,7 +8,6 @@ import kotlinx.datetime.number import kotlinx.datetime.toLocalDateTime import naksha.base.Action import naksha.base.AtomicMap -import naksha.base.Int64 import naksha.model.NakshaVersion import naksha.base.Platform.PlatformCompanion.logger import naksha.jbon.IDictReader @@ -261,7 +260,7 @@ SELECT basics.*, procs.* FROM basics, procs; for (adminCol in listOf(collections, transactions, books, catalogs)) { val tn = TupleNumber( number, catalogNumber, collectionsColNumber, - Int64(adminCol.collectionNumber.toLong()), Int64(1) + adminCol.collectionNumber.toLong(), 1L ) // Set the collection's resolved `_tn` member, where encodeFeature reads it back. val col = adminCol.head @@ -285,10 +284,10 @@ SELECT basics.*, procs.* FROM basics, procs; } var installed_version: NakshaVersion var installed_storage_id: String - var installed_storage_number: Int64 + var installed_storage_number: Long conn.execute("SELECT \"${ADMIN_CATALOG_ID}\".naksha_version() AS v, \"${ADMIN_CATALOG_ID}\".naksha_storage_id() AS id, \"${ADMIN_CATALOG_ID}\".naksha_storage_number() AS n").fetch().use { cursor -> try { - val v: Int64 = cursor["v"] + val v: Long = cursor["v"] installed_version = NakshaVersion(v) installed_storage_id = cursor["id"] installed_storage_number = cursor["n"] @@ -366,7 +365,7 @@ SELECT basics.*, procs.* FROM basics, procs; conn: PgConnection, config: PgConfig, storageId: String, - storageNumber: Int64, + storageNumber: Long, psqlVersion: NakshaVersion ): Int @@ -387,7 +386,7 @@ SELECT basics.*, procs.* FROM basics, procs; conn: PgConnection, config: PgConfig, storageId: String, - storageNumber: Int64, + storageNumber: Long, psqlVersion: NakshaVersion, schemaOid: Int, installedVersion: NakshaVersion? @@ -401,11 +400,11 @@ SELECT basics.*, procs.* FROM basics, procs; * @return the next _(unused)_ transaction-number. * @since 3.0.0 */ - fun getTxn(conn: PgConnection): Int64 { + fun getTxn(conn: PgConnection): Long { val QUERY = "SELECT currval($1) as txn" val cursor = conn.execute(QUERY, arrayOf(versionSequenceOid)).fetch() cursor.use { - val txn: Int64 = cursor["txn"] + val txn: Long = cursor["txn"] return txn } } @@ -423,14 +422,14 @@ SELECT basics.*, procs.* FROM basics, procs; val QUERY = "SELECT nextval($1) as version, (extract(epoch from clock_timestamp())*1000)::int8 as time, (extract(epoch from transaction_timestamp())*1000)::int8 as txn" val cursor = conn.execute(QUERY, arrayOf(versionSequenceOid)).fetch() cursor.use { - var txn: Int64 = cursor["txn"] - var postgresClock: Int64 = cursor["time"] + var txn: Long = cursor["txn"] + var postgresClock: Long = cursor["time"] var postgresInstant = Instant.fromEpochMilliseconds(postgresClock.toLong()) var postgresDate = postgresInstant.toLocalDateTime(TimeZone.UTC) var year = postgresDate.year var month = postgresDate.month.number var day = postgresDate.day - var versionNumber: Int64 = cursor["version"] + var versionNumber: Long = cursor["version"] var version = Version(versionNumber) if (version.isBehind(year, month, day)) { logger.info("Transaction sequence ({}/{}/{}-{}) lags behind real date ({}/{}/{}), acquire advisory lock", @@ -453,7 +452,7 @@ SELECT basics.*, procs.* FROM basics, procs; if (version.isBehind(year, month, day)) { logger.info("Transaction sequence ({}/{}/{}-{}) still lags behind real date ({}/{}/{}), rollover to next day as we now hold the advisory lock", version.month, version.day, version.year, version.seq, month, day, year) - version = Version.auto(year, month, day, Int64(0), Action.VERSION) + version = Version.auto(year, month, day, 0L, Action.VERSION) versionNumber = version.number conn.execute("SELECT setval($1, $2)", arrayOf(versionSequenceOid, versionNumber)).close() // SELECT setval($1, $2); — Next nextval will return $2 + Increment, currval will return $2, no need to add 4! @@ -500,7 +499,7 @@ SELECT basics.*, procs.* FROM basics, procs; val existing = catalogCache[catalogNumber] val existingTn = existing?.head?.tupleNumber - val existingVersion: Int64? = if (existingTn != null && Action.fromVersion(existingTn.version) != Action.DELETE) existingTn.version else null + val existingVersion: Long? = if (existingTn != null && Action.fromVersion(existingTn.version) != Action.DELETE) existingTn.version else null if (existingVersion != null && existingVersion > newVersion) { logger.debug("Do not update catalog '$id', the existing version ($existingVersion) is newer than the new ($newVersion)") break @@ -559,7 +558,7 @@ SELECT basics.*, procs.* FROM basics, procs; conn.use { conn.autoCommit = false setSearchPath(conn) - val versionNumber = Version.now(Int64(1), Action.CREATE).number + val versionNumber = Version.now(1L, Action.CREATE).number for (adminCol in listOf(collections, transactions, catalogs, books)) { if (!adminCol.storeHistory) continue // TODO This creation of history partitions upfront by 3 years is a temporary hack, to be replaced when pg_partman is used @@ -664,4 +663,4 @@ WHERE ${StandardMembers.FeatureNumber} = $1""" @Deprecated("Will be replaced with global books") abstract override fun getEncodingDictionary(feature: Any?, context: Any?): JbDictionary? -} \ No newline at end of file +} diff --git a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgCatalog.kt b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgCatalog.kt index 69ec50456..9cb8bb3ed 100644 --- a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgCatalog.kt +++ b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgCatalog.kt @@ -97,7 +97,7 @@ open class PgCatalog internal constructor( val collectionsColNumber = c.collectionNumber c.head.tupleNumber = TupleNumber( storage.number, catalogNumber, collectionsColNumber, - Int64(collectionsColNumber.toLong()), Int64(1) + collectionsColNumber.toLong(), 1L ) _collections = c } @@ -123,7 +123,7 @@ open class PgCatalog internal constructor( val existing = collectionCache[collectionNumber] val existingTn = existing?.head?.tupleNumber - val existingVersion: Int64? = if (existingTn != null && Action.fromVersion(existingTn.version) != Action.DELETE) existingTn.version else null + val existingVersion: Long? = if (existingTn != null && Action.fromVersion(existingTn.version) != Action.DELETE) existingTn.version else null if (existingVersion != null && existingVersion > newVersion) { logger.debug("Do not update collection '$id', the existing version ($existingVersion) is newer than the new ($newVersion)") break diff --git a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgCollection.kt b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgCollection.kt index 55d771db9..a208e95d2 100644 --- a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgCollection.kt +++ b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgCollection.kt @@ -92,7 +92,7 @@ open class PgCollection internal constructor( * @return the partition index of the [PgHistoryPartition] into which _HEAD_ features will be moved, when modified in the given version. * @since 3.0 */ - fun historyPartitionNumberOf(version: Int64): Int = (version shr shift).toInt() + fun historyPartitionNumberOf(version: Long): Int = (version shr shift).toInt() /** * Convert the given member into a [PgColumn], only fails for the standard member [Tn]. diff --git a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgColumnWithValues.kt b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgColumnWithValues.kt index 033caf0b9..9cba9cd26 100644 --- a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgColumnWithValues.kt +++ b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgColumnWithValues.kt @@ -1,7 +1,6 @@ package naksha.psql import naksha.base.AnyList -import naksha.base.Int64 import naksha.base.Platform.PlatformCompanion.toJSON import naksha.model.objects.MemberType @@ -50,4 +49,4 @@ internal data class PgColumnWithValues( } override fun toString(): String = alias -} \ No newline at end of file +} diff --git a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgConnection.kt b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgConnection.kt index 01f455605..a15d4f544 100644 --- a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgConnection.kt +++ b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgConnection.kt @@ -2,7 +2,6 @@ package naksha.psql -import naksha.base.Int64 import naksha.model.SessionOptions import kotlin.js.ExperimentalJsExport import kotlin.js.JsExport @@ -31,7 +30,7 @@ interface PgConnection : AutoCloseable { * The unique connection identifier of this connection. * @since 3.0 */ - val id: Int64 + val id: Long /** * The URI of the database connection. @@ -81,4 +80,4 @@ interface PgConnection : AutoCloseable { * Terminate the connection, what means closing it, and do not return to connection pool! */ fun terminate() -} \ No newline at end of file +} diff --git a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgHeadTable.kt b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgHeadTable.kt index 570d9669b..c45f702c3 100644 --- a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgHeadTable.kt +++ b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgHeadTable.kt @@ -1,6 +1,5 @@ package naksha.psql -import naksha.base.Int64 import naksha.model.objects.StandardMembers.StandardMembers_C.Id import naksha.psql.PgColumn.PgColumn_C.FnColumn import naksha.psql.PgColumn.PgColumn_C.NextVersionColumn @@ -74,7 +73,7 @@ PARTITION BY RANGE ((($FnColumn & 65535)::int4 % ${collection.partitions}))$TABL = if (partitions.isEmpty()) null else partitions[partitionNumber(featureId) % partitions.size] @JsName("getByFeatureNumber") - operator fun get(featureNumber: Int64): PgDistributionPartition? + operator fun get(featureNumber: Long): PgDistributionPartition? = if (partitions.isEmpty()) null else partitions[featureNumber.toInt() % partitions.size] override fun create(conn: PgConnection) { @@ -117,4 +116,4 @@ PARTITION BY RANGE ((($FnColumn & 65535)::int4 % ${collection.partitions}))$TABL } if (index in indices) indices -= index } -} \ No newline at end of file +} diff --git a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgHistoryPartition.kt b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgHistoryPartition.kt index d6852c090..54cfbf337 100644 --- a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgHistoryPartition.kt +++ b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgHistoryPartition.kt @@ -2,7 +2,6 @@ package naksha.psql -import naksha.base.Int64 import naksha.model.Naksha import naksha.base.NakshaError.NakshaErrorCompanion.PARTITION_NOT_FOUND import naksha.base.NakshaException @@ -73,7 +72,7 @@ PARTITION BY RANGE ((($FnColumn & 65535)::int4 % ${collection.partitions}))$TABL * @since 3.0 */ @JsName("partitionNumberForFeatureNumber") - fun partitionNumber(featureNumber: Int64): Int = Naksha.partitionNumber(featureNumber) % collection.partitions + fun partitionNumber(featureNumber: Long): Int = Naksha.partitionNumber(featureNumber) % collection.partitions /** * Calculates the partition-number from the given [feature-id][Id]. @@ -90,7 +89,7 @@ PARTITION BY RANGE ((($FnColumn & 65535)::int4 % ${collection.partitions}))$TABL * @return either the distribution-partition to put the feature into or `null` if the table is not partitioned, features need to be written into the table itself. */ @JsName("getByFeatureNumber") - operator fun get(featureNumber: Int64): PgDistributionPartition? { + operator fun get(featureNumber: Long): PgDistributionPartition? { val partitions = this.partitions if (partitions.isEmpty()) return null val i = Naksha.partitionNumber(featureNumber) % collection.partitions @@ -152,4 +151,4 @@ PARTITION BY RANGE ((($FnColumn & 65535)::int4 % ${collection.partitions}))$TABL } if (index in indices) indices -= index } -} \ No newline at end of file +} diff --git a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgHistoryTable.kt b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgHistoryTable.kt index a519f5dfd..f7ad19270 100644 --- a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgHistoryTable.kt +++ b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgHistoryTable.kt @@ -2,7 +2,6 @@ package naksha.psql -import naksha.base.Int64 import naksha.model.objects.StandardMembers.StandardMembers_C.Id import naksha.model.objects.StandardMembers.StandardMembers_C.NextVersion import naksha.psql.PgColumn.PgColumn_C.FnColumn @@ -70,11 +69,11 @@ $TABLESPACE""" * @return the calculated partition-number. * @since 3.0 */ - fun partitionNumber(nextVersion: Int64): Int = (nextVersion shr collection.shift).toInt() + fun partitionNumber(nextVersion: Long): Int = (nextVersion shr collection.shift).toInt() - operator fun get(nextVersion: Int64): PgHistoryPartition? = partitions[partitionNumber(nextVersion)] + operator fun get(nextVersion: Long): PgHistoryPartition? = partitions[partitionNumber(nextVersion)] - operator fun set(nextVersion: Int64, partition: PgHistoryPartition) { + operator fun set(nextVersion: Long, partition: PgHistoryPartition) { partitions[partitionNumber(nextVersion)] = partition } diff --git a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgLock.kt b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgLock.kt index 73d05c3d7..662b74571 100644 --- a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgLock.kt +++ b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgLock.kt @@ -3,7 +3,6 @@ package naksha.psql import naksha.base.AtomicInt -import naksha.base.Int64 import naksha.model.* import naksha.base.NakshaError.NakshaErrorCompanion.ILLEGAL_STATE import naksha.base.NakshaException @@ -46,7 +45,7 @@ internal class PgLock internal constructor( * The lock-number generated from the lock-id. * @since 3.0.0 */ - val lockNumber: Int64 = PgUtil.lockId(lockId) + val lockNumber: Long = PgUtil.lockId(lockId) init { if (isSessionLock) { @@ -71,4 +70,4 @@ internal class PgLock internal constructor( } override fun isClosed(): Boolean = closed.get() <= 0 || conn != session.pgConnection -} \ No newline at end of file +} diff --git a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgQuery.kt b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgQuery.kt index 1f0cac441..959e970e0 100644 --- a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgQuery.kt +++ b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgQuery.kt @@ -1,6 +1,5 @@ package naksha.psql -import naksha.base.Int64 /** * An SQL query to be executed against a Naksha table. @@ -32,7 +31,7 @@ data class PgQuery( * The storage-number of the storage from which the results are. * @since 3.0 */ - val storageNumber: Int64, + val storageNumber: Long, /** * The map-number of the map from which the results are. @@ -72,4 +71,4 @@ data class PgQuery( result = 31 * result + argTypes.contentHashCode() return result } -} \ No newline at end of file +} diff --git a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgQueryBuilder.kt b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgQueryBuilder.kt index f3fc8277d..503cfa905 100644 --- a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgQueryBuilder.kt +++ b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgQueryBuilder.kt @@ -1,6 +1,5 @@ package naksha.psql -import naksha.base.Int64 import naksha.base.Version import naksha.base.collectionNotFound import naksha.base.illegalArg @@ -80,7 +79,7 @@ class PgQueryBuilder(val session: PgSession, val readRequest: ReadRequest) { val WHERE = StringBuilder() var version = req.version if (version != null) { - version = version or Int64(3) + version = version or 3L if (version == Version.HEAD.number) { version = null // HEAD } else { @@ -90,7 +89,7 @@ class PgQueryBuilder(val session: PgSession, val readRequest: ReadRequest) { } var minVersion = req.minVersion if (minVersion != null) { - minVersion = minVersion or Int64(3) + minVersion = minVersion or 3L if (WHERE.isNotEmpty()) WHERE.append(" AND ") WHERE.append("($VERSION >= ").append(minVersion).append(")") } @@ -154,4 +153,4 @@ SELECT $FN AS fn, $VERSION AS version FROM limited""" pgCollection.collectionNumber ) } -} \ No newline at end of file +} diff --git a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgQueryWhereBuilder.kt b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgQueryWhereBuilder.kt index f5ec62d68..9da6c68b9 100644 --- a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgQueryWhereBuilder.kt +++ b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgQueryWhereBuilder.kt @@ -1,7 +1,6 @@ package naksha.psql import naksha.base.AnyList -import naksha.base.Int64 import naksha.base.StringList import naksha.model.Naksha import naksha.base.NakshaError @@ -396,7 +395,7 @@ internal class PgQueryWhereBuilder(private val request: ReadFeatures, private va } private fun _TagGt(negate: Boolean, memberName: String, key: String, value: Any?) { - if (value !is Number && value !is Int64) { + if (value !is Number) { throw illegalArg("TagGt: The given value is number: '$value'") } val expression = if (negate) "@ <= $value" else "@ > $value" @@ -404,7 +403,7 @@ internal class PgQueryWhereBuilder(private val request: ReadFeatures, private va } private fun _TagGte(negate: Boolean, memberName: String, key: String, value: Any?) { - if (value !is Number && value !is Int64) { + if (value !is Number) { throw illegalArg("TagGte: The given value is number: '$value'") } val expression = if (negate) "@ < $value" else "@ >= $value" @@ -412,7 +411,7 @@ internal class PgQueryWhereBuilder(private val request: ReadFeatures, private va } private fun _TagLt(negate: Boolean, memberName: String, key: String, value: Any?) { - if (value !is Number && value !is Int64) { + if (value !is Number) { throw illegalArg("TagLt: The given value is no number: '$value'") } val expression = if (negate) "@ >= $value" else "@ < $value" @@ -420,7 +419,7 @@ internal class PgQueryWhereBuilder(private val request: ReadFeatures, private va } private fun _TagLte(negate: Boolean, memberName: String, key: String, value: Any?) { - if (value !is Number && value !is Int64) { + if (value !is Number) { throw illegalArg("The given value is no valid tag value (number expected): $value") } val expression = if (negate) "@ > $value" else "@ <= $value" @@ -565,7 +564,6 @@ internal class PgQueryWhereBuilder(private val request: ReadFeatures, private va is Short -> PgType.SHORT is Int -> PgType.INT is Long -> PgType.INT64 - is Int64 -> PgType.INT64 is Float -> PgType.FLOAT is Double -> PgType.DOUBLE is ByteArray -> PgType.BYTE_ARRAY @@ -578,7 +576,7 @@ internal class PgQueryWhereBuilder(private val request: ReadFeatures, private va /** * Returns a placeholder string like `$1` for the given value, and add the values and its type into the value and type arrays. - * @param value any number _(including `Int64`)_ + * @param value any number * @return */ private fun placeholderForNumber(value: Any?): String { @@ -664,12 +662,12 @@ internal class PgQueryWhereBuilder(private val request: ReadFeatures, private va private fun whereFeatureId() { // Partition into numeric IDs (fn >= 0, id stored as NULL in DB) and named IDs (fn < 0, id NOT NULL). val reqIds: StringList = request.featureIds - val featureNumbers: MutableList = mutableListOf() + val featureNumbers: MutableList = mutableListOf() val featureIds: MutableList = mutableListOf() for (id in reqIds) { if (id == null) continue val fn = Naksha.featureNumber(id) - if (fn >= Int64(0)) { + if (fn >= 0L) { featureNumbers.add(fn) } else { featureIds.add(id) diff --git a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgReader.kt b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgReader.kt index 28fc3a54d..c5de97848 100644 --- a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgReader.kt +++ b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgReader.kt @@ -61,8 +61,8 @@ class PgReader( val collectionNumber = query.collectionNumber while (cursor.next()) { val col_num: Int = collectionNumber ?: cursor["col_num"] - val fn: naksha.base.Int64 = cursor["fn"] - val version: naksha.base.Int64 = cursor["version"] + val fn: Long = cursor["fn"] + val version: Long = cursor["version"] featureTuples.add(FeatureTuple(TupleNumber(storageNumber, mapNumber, col_num, fn, version))) } } diff --git a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgRows.kt b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgRows.kt index e5edda67e..d66ac7e4b 100644 --- a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgRows.kt +++ b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgRows.kt @@ -1,7 +1,6 @@ package naksha.psql import naksha.base.AnyList -import naksha.base.Int64 import naksha.geo.SpGeometry import naksha.jbon.BookType import naksha.jbon.HeapBook @@ -118,7 +117,7 @@ internal class PgRows { * If all rows are coming from the same storage, the storage-number of it. * @since 3.0 */ - var databaseNumber: Int64? = null + var databaseNumber: Long? = null set(value) { collection = null field = value @@ -127,7 +126,7 @@ internal class PgRows { /** * @see [databaseNumber] */ - fun withDatabaseNumber(value: Int64): PgRows { + fun withDatabaseNumber(value: Long): PgRows { databaseNumber = value return this } @@ -255,7 +254,7 @@ internal class PgRows { null } } - fun getB64(row: Int, columnName: String, featureNumber: Int64): TupleNumber? { + fun getB64(row: Int, columnName: String, featureNumber: Long): TupleNumber? { val raw = getByteArray(row, columnName) ?: return null val storageNumber = this.databaseNumber ?: return null val mapNumber = this.catalogNumber ?: return null @@ -305,15 +304,15 @@ internal class PgRows { if (member.isVirtual()) continue when (name) { Tn.name -> { - val fn = getColumn(PgColumn.FnColumn.name)?.values?.get(row) as? Int64 - val ver = getColumn(PgColumn.VersionColumn.name)?.values?.get(row) as? Int64 + val fn = getColumn(PgColumn.FnColumn.name)?.values?.get(row) as? Long + val ver = getColumn(PgColumn.VersionColumn.name)?.values?.get(row) as? Long val db = databaseNumber; val cat = catalogNumber; val col = collectionNumber val tn = if (fn != null && ver != null && db != null && cat != null && col != null) TupleNumber(db, cat, col, fn, ver) else null membersBook.put(name, tn) } NextVersion.name -> { - val raw = getColumn(name)?.values?.get(row) as? Int64 + val raw = getColumn(name)?.values?.get(row) as? Long membersBook.put(name, raw ?: Version.HEAD.number) } else -> { @@ -394,7 +393,7 @@ internal class PgRows { getColumn(PgColumn.NextVersionColumn.name)?.let { if (it.values[row] == Version.HEAD.number) it.values[row] = null } // `_id` is materialized only when it is not derivable from the feature-number: fn < 0 => hashed // id, fn >= 0 => id equals fn so `_id` stays NULL (a CHECK enforces both cases). - getColumn(Id.name)?.let { it.values[row] = if (tn.featureNumber.toLong() < 0L) membersBook[Id.name] else null } + getColumn(Id.name)?.let { it.values[row] = if (tn.featureNumber < 0L) membersBook[Id.name] else null } val featureColumn = getColumn(FeatureBytes.name) ?: return featureColumn.values[row] = tuple.featureBytes } diff --git a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgSession.kt b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgSession.kt index 5612e7b83..1d27bbb60 100644 --- a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgSession.kt +++ b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgSession.kt @@ -4,7 +4,6 @@ package naksha.psql import naksha.base.* import naksha.base.Platform.PlatformCompanion.logger -import naksha.base.Platform.PlatformCompanion.longToInt64 import naksha.base.Platform.PlatformCompanion.newAtomicInt64 import naksha.base.PlatformDataViewApi.PlatformDataViewApiCompanion.dataview_set_int64 import naksha.model.* @@ -50,8 +49,8 @@ open class PgSession( ) : IWriteSession, IReadSession, ISession { companion object PgSession_C { - private val nextSessionId = newAtomicInt64(longToInt64(0L)) - private val ONE = longToInt64(1L) + private val nextSessionId = newAtomicInt64(0L) + private const val ONE = 1L // Decodes each 16-byte entry of `$1::bytea[]` into `(fn, version)` bigints (big-endian halves). private const val TUPLE_LOOKUP_CTE: String = @@ -83,7 +82,7 @@ open class PgSession( * A unique numerical identifier for the session. * @since 3.0 */ - val id: Int64 = nextSessionId.getAndAdd(ONE) + val id: Long = nextSessionId.getAndAdd(ONE) override val storage = pgStorage @@ -200,7 +199,7 @@ open class PgSession( * If a connection is backing this session currently, return the [id][PgConnection.id] of the [connection][PgConnection], otherwise `null`. * @since 3.0 */ - val connectionId: Int64? + val connectionId: Long? get() = pgConnection?.id /** diff --git a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgTxn.kt b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgTxn.kt index 4ad77c1a3..dcac0f176 100644 --- a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgTxn.kt +++ b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgTxn.kt @@ -2,7 +2,6 @@ package naksha.psql -import naksha.base.Int64 import naksha.base.Version import kotlin.js.ExperimentalJsExport import kotlin.js.JsExport @@ -17,16 +16,16 @@ data class PgTxn( * The transaction-number. * @since 3.0.0 */ - val number: Int64, + val number: Long, /** * The Epoch timestamp _(milliseconds since 1 January 1970)_ when the transaction started. * @since 3.0.0 */ - val epoch: Int64, + val epoch: Long, /** * The version object, created from [number]. */ val version: Version = Version(number) -) \ No newline at end of file +) diff --git a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgType.kt b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgType.kt index 652a1bd73..b9acf551d 100644 --- a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgType.kt +++ b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgType.kt @@ -3,7 +3,6 @@ package naksha.psql import naksha.base.AnyList -import naksha.base.Int64 import naksha.base.JsEnum import naksha.base.ListProxy import naksha.base.Platform.PlatformCompanion.toJSON @@ -331,8 +330,8 @@ class PgType : JsEnum() { ?: throw illegalArg("The given value is not a boolean: $value") SHORT, INT -> (value as? Number?)?.toInt() ?: throw illegalArg("The given value is no number: $value") - INT64 -> if (value is Number) value.toLong() else if (value is Int64) value.toLong() - else throw illegalArg("The given value is no number: $value") + INT64 -> (value as? Number?)?.toLong() + ?: throw illegalArg("The given value is no number: $value") FLOAT -> (value as? Number?)?.toFloat() ?: throw illegalArg("The given value is no number: $value") DOUBLE -> (value as? Number?)?.toDouble() @@ -357,4 +356,4 @@ class PgType : JsEnum() { else -> throw internalError("Missing when-case for this Postgres Type: $this") } } -} \ No newline at end of file +} diff --git a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgUtil.kt b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgUtil.kt index ee15cd9dc..4484c4afa 100644 --- a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgUtil.kt +++ b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgUtil.kt @@ -200,6 +200,6 @@ class PgUtil private constructor() { */ @JsStatic @JvmStatic - fun lockId(name: String): Int64 = Fnv1a64.string(Fnv1a64.start(), name) + fun lockId(name: String): Long = Fnv1a64.string(Fnv1a64.start(), name) } -} \ No newline at end of file +} diff --git a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgWrite.kt b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgWrite.kt index 354b1def0..db97d67d1 100644 --- a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgWrite.kt +++ b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgWrite.kt @@ -76,9 +76,9 @@ internal data class PgWrite(val original: Write, val i: Int) { * This is the authoritative routing key for physical partition assignment. * @since 3.0 */ - val featureNumber: naksha.base.Int64 = when (original.collectionId) { - Naksha.COLLECTIONS_COL_ID -> naksha.base.Int64(Naksha.collectionNumber(id)) - Naksha.CATALOGS_COL_ID -> naksha.base.Int64(Naksha.catalogNumber(id)) + val featureNumber: Long = when (original.collectionId) { + Naksha.COLLECTIONS_COL_ID -> Naksha.collectionNumber(id).toLong() + Naksha.CATALOGS_COL_ID -> Naksha.catalogNumber(id).toLong() else -> Naksha.featureNumber(id) } @@ -174,4 +174,4 @@ internal data class PgWrite(val original: Write, val i: Int) { * @since 3.0 */ var tupleNumber: TupleNumber? = null -} \ No newline at end of file +} diff --git a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgWriterBase.kt b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgWriterBase.kt index d6b0ca826..6a4768b52 100644 --- a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgWriterBase.kt +++ b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgWriterBase.kt @@ -1,6 +1,5 @@ package naksha.psql -import naksha.base.Int64 import naksha.base.IntMutable import naksha.base.fn.Fx3 import naksha.model.Tuple @@ -58,7 +57,7 @@ internal abstract class PgWriterBase protected constructor( val session: PgSession get() = pgWriter.session - val storageNumber: Int64 + val storageNumber: Long get() = pgCollection.storage.number val catalogNumber: Int diff --git a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgWriterUpdate.kt b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgWriterUpdate.kt index d6e90154b..bbc3ba29c 100644 --- a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgWriterUpdate.kt +++ b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgWriterUpdate.kt @@ -1,6 +1,5 @@ package naksha.psql -import naksha.base.Int64 import naksha.base.Platform import naksha.base.Platform.PlatformCompanion.logger import naksha.base.PlatformUtil @@ -31,7 +30,7 @@ internal class PgWriterUpdate( // All columns that are BYTE_ARRAYs (can be empty) private val byteArrayCols = pgCollection.columns.filter { it.memberType == MemberType.BYTE_ARRAY } - private val writeByFn = mutableMapOf() + private val writeByFn = mutableMapOf() init { inRows.addColumns(pgCollection.columns) inRows.addColumn("expected_version", MemberType.INT64) // needed to do atomic updates @@ -161,7 +160,7 @@ LEFT JOIN inserted ON inserted.$FnColumn = new_row.$FnColumn val version = outRows.getLong(row, VersionColumn) ?: throw illegalState("Column '$VersionColumn' in result must not be null") val newTn = TupleNumber(storageNumber, catalogNumber, collectionNumber, fn, version) val pgWrite = writeByFn[fn] ?: throw illegalState("Missing write record for feature-number: $fn") - val expected_version: Int64? = pgWrite.version?.number + val expected_version: Long? = pgWrite.version?.number // Feature should have existed. val existing_fn = outRows.getLong(row, "_existing_fn") @@ -178,7 +177,7 @@ LEFT JOIN inserted ON inserted.$FnColumn = new_row.$FnColumn // We should have updated the feature val inserted_fn = outRows.getLong(row, "_inserted_fn") ?: { // The only defined reason is that the expected version did not match. - if (expected_version != null && (expected_version and Int64(-4)) != (existing_version and Int64(-4))) { + if (expected_version != null && (expected_version and -4L) != (existing_version and -4L)) { throw conflict("Atomic update failed, feature '${pgWrite.id}' was expected in version $existing_version, but found to be in $existing_version") } // Otherwise, there is an internal error. @@ -204,4 +203,4 @@ LEFT JOIN inserted ON inserted.$FnColumn = new_row.$FnColumn } } } -} \ No newline at end of file +} diff --git a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgWriterUpsert.kt b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgWriterUpsert.kt index 041288cb3..8622d342a 100644 --- a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgWriterUpsert.kt +++ b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgWriterUpsert.kt @@ -1,7 +1,6 @@ package naksha.psql import naksha.base.Action -import naksha.base.Int64 import naksha.base.Platform import naksha.base.Platform.PlatformCompanion.logger import naksha.base.PlatformUtil @@ -29,7 +28,7 @@ internal class PgWriterUpsert( // All columns that are BYTE_ARRAYs (can be empty) private val byteArrayCols = pgCollection.columns.filter { it.memberType == MemberType.BYTE_ARRAY } - private val writeByFn = mutableMapOf() + private val writeByFn = mutableMapOf() init { inRows.addColumns(pgCollection.columns) loadAllTuple { _, tuple, pgWrite -> writeByFn[tuple.tupleNumber.featureNumber] = pgWrite } diff --git a/here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/ChainCollectionTest.kt b/here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/ChainCollectionTest.kt index 049700683..9bc8cb9e8 100644 --- a/here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/ChainCollectionTest.kt +++ b/here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/ChainCollectionTest.kt @@ -1,6 +1,5 @@ package naksha.psql -import naksha.base.Int64 import naksha.model.objects.Index import naksha.model.objects.Member import naksha.model.objects.MemberType @@ -50,17 +49,15 @@ class ChainCollectionTest : PgTestBase( private fun makeFeature(fn: Long, leftFn: Long?, rightFn: Long?): NakshaFeature { val f = NakshaFeature(fn.toString()) - if (leftFn != null) f.properties["left_fn"] = Int64(leftFn) - if (rightFn != null) f.properties["right_fn"] = Int64(rightFn) + if (leftFn != null) f.properties["left_fn"] = leftFn + if (rightFn != null) f.properties["right_fn"] = rightFn return f } - /** Coerces any numeric type (Long, Int, Int64) to Int64 for assertion. */ - private fun toInt64(v: Any?): Int64? = when (v) { + /** Coerces any numeric type to Long for assertion. */ + private fun toLong(v: Any?): Long? = when (v) { null -> null - is Int64 -> v - is Long -> Int64(v) - is Int -> Int64(v.toLong()) + is Number -> v.toLong() else -> null } @@ -102,37 +99,37 @@ class ChainCollectionTest : PgTestBase( // Then: verify head val headBack = assertNotNull(response.features.find { it?.id == headFn.toString() }) - assertEquals(Int64(headFn), XyzTn.get(headBack)?.featureNumber) + assertEquals(headFn, XyzTn.get(headBack)?.featureNumber) assertNull( headBack.properties["left_fn"], "head.left_fn should be null" ) assertEquals( - Int64(midFn), - toInt64(headBack.properties["right_fn"]), + midFn, + toLong(headBack.properties["right_fn"]), "head.right_fn should point to mid" ) // Then: verify mid val midBack = assertNotNull(response.features.find { it?.id == midFn.toString() }) - assertEquals(Int64(midFn), XyzTn.get(midBack)?.featureNumber) + assertEquals(midFn, XyzTn.get(midBack)?.featureNumber) assertEquals( - Int64(headFn), - toInt64(midBack.properties["left_fn"]), + headFn, + toLong(midBack.properties["left_fn"]), "mid.left_fn should point to head" ) assertEquals( - Int64(tailFn), - toInt64(midBack.properties["right_fn"]), + tailFn, + toLong(midBack.properties["right_fn"]), "mid.right_fn should point to tail" ) // Then: verify tail val tailBack = assertNotNull(response.features.find { it?.id == tailFn.toString() }) - assertEquals(Int64(tailFn), XyzTn.get(tailBack)?.featureNumber) + assertEquals(tailFn, XyzTn.get(tailBack)?.featureNumber) assertEquals( - Int64(midFn), - toInt64(tailBack.properties["left_fn"]), + midFn, + toLong(tailBack.properties["left_fn"]), "tail.left_fn should point to mid" ) assertNull( @@ -189,7 +186,7 @@ class ChainCollectionTest : PgTestBase( // Then: find the feature whose right_fn == tailFn (that must be mid) val candidate = all.features.find { f -> - f != null && toInt64(f.properties["right_fn"]) == Int64(tailFn) + f != null && toLong(f.properties["right_fn"]) == tailFn } assertNotNull(candidate, "No feature with right_fn == tailFn found") assertEquals(midFn.toString(), candidate.id) diff --git a/here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/DeleteFeatureBase.kt b/here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/DeleteFeatureBase.kt index ce062c542..a8c58d9e4 100644 --- a/here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/DeleteFeatureBase.kt +++ b/here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/DeleteFeatureBase.kt @@ -1,7 +1,6 @@ package naksha.psql import naksha.base.Action -import naksha.base.Int64 import naksha.model.* import naksha.model.objects.NakshaCollection import naksha.model.objects.NakshaFeature @@ -91,8 +90,8 @@ abstract class DeleteFeatureBase( @Test fun tombstoneVersionMustCarryDeleteTransactionAndDeletedActionBits() { val featureId = "feature_version_bits_check" - val ACTION_MASK = Int64(3L) // lower 2 bits - val ACTION_CLEAR = Int64(-4L) // clear lower 2 bits + val ACTION_MASK = 3L // lower 2 bits + val ACTION_CLEAR = -4L // clear lower 2 bits // CREATE — capture the create-transaction's version (txn with lower 2 bits = 0 = CREATED). val createdTn = assertNotNull( diff --git a/here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/InsertFeatureTest.kt b/here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/InsertFeatureTest.kt index 6a3841ddb..3e9138fa6 100644 --- a/here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/InsertFeatureTest.kt +++ b/here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/InsertFeatureTest.kt @@ -1,7 +1,6 @@ package naksha.psql import naksha.base.Action -import naksha.base.Int64 import naksha.base.NakshaError import naksha.base.Platform import naksha.base.Version @@ -124,8 +123,8 @@ class InsertFeatureTest : PgTestBase() { // And: val retrievedFeature = retrievedFeatures.find { it?.id == featureToCreate.id } assertNotNull(retrievedFeature, "Missing feature with id: ${featureToCreate.id}") - assertEquals(Int64(featureNumber), retrievedFeature.properties.xyz.guid?.tupleNumber?.featureNumber) - assertEquals(Int64(featureNumber), retrievedFeature.properties.xyz.guid?.tupleNumber?.featureNumber) + assertEquals(featureNumber, retrievedFeature.properties.xyz.guid?.tupleNumber?.featureNumber) + assertEquals(featureNumber, retrievedFeature.properties.xyz.guid?.tupleNumber?.featureNumber) assertThatFeature(retrievedFeature) .isIdenticalTo( other = featureToCreate, diff --git a/here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/MemberValueMaterializationTest.kt b/here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/MemberValueMaterializationTest.kt index de7a60264..b2be6a35b 100644 --- a/here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/MemberValueMaterializationTest.kt +++ b/here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/MemberValueMaterializationTest.kt @@ -1,6 +1,5 @@ package naksha.psql -import naksha.base.Int64 import naksha.model.objects.IndexList import naksha.model.objects.JsonPath import naksha.model.objects.Member @@ -39,7 +38,6 @@ class MemberValueMaterializationTest : PgTestBase(collection = null, catalogId = private fun asLong(value: Any?): Long { assertNotNull(value, "expected a numeric column value, got null") return when (value) { - is Int64 -> value.toLong() is Number -> value.toLong() else -> error("expected a numeric column value, got ${value::class.simpleName}") } diff --git a/here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/ReadFeaturesByOtherTns.kt b/here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/ReadFeaturesByOtherTns.kt index 0d5663783..83f634adf 100644 --- a/here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/ReadFeaturesByOtherTns.kt +++ b/here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/ReadFeaturesByOtherTns.kt @@ -1,6 +1,5 @@ package naksha.psql -import naksha.base.Int64 import naksha.model.RandomFeatures.RandomFeatures_C.randomFeatures import naksha.model.objects.NakshaCollection import naksha.model.objects.StandardMembers @@ -39,7 +38,7 @@ class ReadFeaturesByOtherTns : PgTestBase( val updateResp = executeWrite(update) // And: the shared `next_version` of all updated features (all 5 updates ran in one transaction). - val updatedVersion: Int64 = updateResp.features[0]!!.properties.xyz.guid!!.tupleNumber.version + val updatedVersion: Long = updateResp.features[0]!!.properties.xyz.guid!!.tupleNumber.version // When: querying for features whose `next_version` matches that version val byNextTnResp = executeRead(ReadFeatures().apply { @@ -61,4 +60,4 @@ class ReadFeaturesByOtherTns : PgTestBase( assertThatFeature(fetchedPredecessor).isIdenticalTo(initialState) } } -} \ No newline at end of file +} diff --git a/here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/UpdateFeatureTest.kt b/here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/UpdateFeatureTest.kt index 49ae9b3f6..8cae3b079 100644 --- a/here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/UpdateFeatureTest.kt +++ b/here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/UpdateFeatureTest.kt @@ -2,7 +2,6 @@ package naksha.psql import naksha.base.Action import naksha.base.Guid -import naksha.base.Int64 import naksha.base.NakshaError import naksha.base.TupleNumber import naksha.base.Version @@ -130,9 +129,9 @@ class UpdateFeatureTest : PgTestBase(collection = null, catalogId = "") { assertEquals(createdTuple.getByteArray(naksha.model.objects.XyzMembers.XyzReferencePoint), updatedTuple.getByteArray(naksha.model.objects.XyzMembers.XyzReferencePoint)) assertNull(createdTuple.decodeFeature(null)?.properties["new_attr"]) assertEquals("some_value", updatedTuple.decodeFeature(null)?.properties["new_attr"]) - assertEquals(createdTuple.getLong(naksha.model.objects.XyzMembers.XyzCreatedAt)?.let { if (it == Int64(0L)) null else it } ?: createdTuple.getLong(naksha.model.objects.XyzMembers.XyzUpdatedAt), updatedTuple.getLong(naksha.model.objects.XyzMembers.XyzCreatedAt)?.let { if (it == Int64(0L)) null else it }) + assertEquals(createdTuple.getLong(naksha.model.objects.XyzMembers.XyzCreatedAt)?.let { if (it == 0L) null else it } ?: createdTuple.getLong(naksha.model.objects.XyzMembers.XyzUpdatedAt), updatedTuple.getLong(naksha.model.objects.XyzMembers.XyzCreatedAt)?.let { if (it == 0L) null else it }) assertNotEquals(updatedTuple.getLong(naksha.model.objects.XyzMembers.XyzCreatedAt), updatedTuple.getLong(naksha.model.objects.XyzMembers.XyzUpdatedAt)) - assertNull(createdTuple.getLong(naksha.model.objects.XyzMembers.XyzCreatedAt)?.let { if (it == Int64(0L)) null else it }) + assertNull(createdTuple.getLong(naksha.model.objects.XyzMembers.XyzCreatedAt)?.let { if (it == 0L) null else it }) assertNotNull(createdTuple.getLong(naksha.model.objects.XyzMembers.XyzUpdatedAt)) assertEquals(createdTuple.getInt(naksha.model.objects.XyzMembers.XyzHereTile), updatedTuple.getInt(naksha.model.objects.XyzMembers.XyzHereTile)) assertEquals(Action.UPDATE, updatedTuple.tupleNumber.action) @@ -159,7 +158,7 @@ class UpdateFeatureTest : PgTestBase(collection = null, catalogId = "") { testWithCollection("atomicUpdateNotExistingWithFakeUuid") val featureId = "feature_not_existing" - val fakeUUID = TupleNumber(storage.number, catalog.catalogNumber, collection.collectionNumber, Naksha.featureNumber(featureId), Version.now(Int64(1), Action.CREATE).number) + val fakeUUID = TupleNumber(storage.number, catalog.catalogNumber, collection.collectionNumber, Naksha.featureNumber(featureId), Version.now(1L, Action.CREATE).number) val feature = NakshaFeature().apply { id = featureId properties.xyz.setRaw("uuid", fakeUUID) diff --git a/here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/UpgradeStorageTest.kt b/here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/UpgradeStorageTest.kt index 6983560a3..560f9d9f5 100644 --- a/here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/UpgradeStorageTest.kt +++ b/here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/UpgradeStorageTest.kt @@ -1,6 +1,5 @@ package naksha.psql -import naksha.base.Int64 import naksha.base.Platform import naksha.model.Naksha import naksha.model.NakshaVersion @@ -14,8 +13,8 @@ class UpgradeStorageTest : PgTestBase() { // Ensure that the current version is what we expect. storage.adminConnection().use { conn -> conn.execute("SELECT naksha_version() AS v").fetch().use { cursor -> - val installedVersion: Int64 = cursor["v"] - assertEquals(expect.toInt64(), installedVersion) + val installedVersion: Long = cursor["v"] + assertEquals(expect.toLong(), installedVersion) } } } diff --git a/here-naksha-lib-psql/src/jsMain/kotlin/naksha/psql/Plv8Connection.kt b/here-naksha-lib-psql/src/jsMain/kotlin/naksha/psql/Plv8Connection.kt index 1de791f28..39004abce 100644 --- a/here-naksha-lib-psql/src/jsMain/kotlin/naksha/psql/Plv8Connection.kt +++ b/here-naksha-lib-psql/src/jsMain/kotlin/naksha/psql/Plv8Connection.kt @@ -1,6 +1,5 @@ package naksha.psql -import naksha.base.Int64 import naksha.model.SessionOptions /** @@ -15,7 +14,7 @@ class Plv8Connection : PgConnection { get() = TODO("Not yet implemented") set(value) {} - override val id: Int64 + override val id: Long get() = TODO("Not yet implemented") override fun toUri(showPassword: Boolean): String { @@ -49,4 +48,4 @@ class Plv8Connection : PgConnection { override fun terminate() { TODO("Not yet implemented") } -} \ No newline at end of file +} diff --git a/here-naksha-lib-psql/src/jsMain/kotlin/naksha/psql/Plv8Trigger.kt b/here-naksha-lib-psql/src/jsMain/kotlin/naksha/psql/Plv8Trigger.kt index a910348a0..9650a6458 100644 --- a/here-naksha-lib-psql/src/jsMain/kotlin/naksha/psql/Plv8Trigger.kt +++ b/here-naksha-lib-psql/src/jsMain/kotlin/naksha/psql/Plv8Trigger.kt @@ -4,7 +4,6 @@ package naksha.psql import kotlinx.js.JsPlainObject -import naksha.base.Int64 import naksha.model.Tuple import kotlin.js.ExperimentalJsExport import kotlin.js.JsExport @@ -24,12 +23,12 @@ internal const val TG_LEVEL_STATEMENT = "STATEMENT" */ @JsPlainObject external interface Plv8Row { - var created_at: Int64? - var updated_at: Int64? - var author_ts: Int64? - var txn_next: Int64? - var txn: Int64? - var ptxn: Int64? + var created_at: Long? + var updated_at: Long? + var author_ts: Long? + var txn_next: Long? + var txn: Long? + var ptxn: Long? var uid: Int? var puid: Int? var hash: Int? diff --git a/here-naksha-lib-psql/src/jvmMain/kotlin/naksha/psql/PsqlAdminCatalog.kt b/here-naksha-lib-psql/src/jvmMain/kotlin/naksha/psql/PsqlAdminCatalog.kt index c3a21f8ff..e0360fa12 100644 --- a/here-naksha-lib-psql/src/jvmMain/kotlin/naksha/psql/PsqlAdminCatalog.kt +++ b/here-naksha-lib-psql/src/jvmMain/kotlin/naksha/psql/PsqlAdminCatalog.kt @@ -31,11 +31,11 @@ class PsqlAdminCatalog internal constructor( return null } - override fun createAdminCatalog(conn: PgConnection, config: PgConfig, storageId: String, storageNumber: Int64, psqlVersion: NakshaVersion): Int { + override fun createAdminCatalog(conn: PgConnection, config: PgConfig, storageId: String, storageNumber: Long, psqlVersion: NakshaVersion): Int { return upsertAdminMap(conn, storageId, storageNumber, psqlVersion, null, null) } - override fun upgradeAdminCatalog(conn: PgConnection, config: PgConfig, storageId: String, storageNumber: Int64, psqlVersion: NakshaVersion, schemaOid: Int, installedVersion: NakshaVersion?) { + override fun upgradeAdminCatalog(conn: PgConnection, config: PgConfig, storageId: String, storageNumber: Long, psqlVersion: NakshaVersion, schemaOid: Int, installedVersion: NakshaVersion?) { upsertAdminMap(conn, storageId, storageNumber, psqlVersion, schemaOid, installedVersion) } @@ -46,7 +46,7 @@ class PsqlAdminCatalog internal constructor( private fun upsertAdminMap( conn: PgConnection, storageId: String, - storageNumber: Int64, + storageNumber: Long, psqlVersion: NakshaVersion, schemaOid: Int?, installedVersion: NakshaVersion? @@ -157,7 +157,7 @@ class PsqlAdminCatalog internal constructor( ) logger.info("Create transaction-seq, map-sequence, and collection-sequence ...") // For a version number, the lower two bit must be always set. - val START_VERSION = Version.now(0.toInt64(), Action.VERSION) + val START_VERSION = Version.now(0L, Action.VERSION) conn.execute("CREATE SEQUENCE IF NOT EXISTS $NAKSHA_VERSION_SEQ AS ${PgType.INT64} START ${START_VERSION.number} INCREMENT BY 4 CACHE 1;").close() logger.info("Create internal collections: transactions, collections, and dictionaries") @@ -250,4 +250,4 @@ class PsqlAdminCatalog internal constructor( */ internal fun start() { } -} \ No newline at end of file +} diff --git a/here-naksha-lib-psql/src/jvmMain/kotlin/naksha/psql/PsqlConnection.kt b/here-naksha-lib-psql/src/jvmMain/kotlin/naksha/psql/PsqlConnection.kt index ca3ffb1ee..2d276337b 100644 --- a/here-naksha-lib-psql/src/jvmMain/kotlin/naksha/psql/PsqlConnection.kt +++ b/here-naksha-lib-psql/src/jvmMain/kotlin/naksha/psql/PsqlConnection.kt @@ -1,6 +1,5 @@ package naksha.psql -import naksha.base.Int64 import naksha.base.NakshaError.NakshaErrorCompanion.ILLEGAL_STATE import naksha.base.NakshaException import naksha.model.SessionOptions @@ -17,7 +16,7 @@ import java.lang.ref.WeakReference */ class PsqlConnection internal constructor( val instance: PsqlInstance, - override val id: Int64, + override val id: Long, jdbc: org.postgresql.jdbc.PgConnection, options: SessionOptions ) : PgConnection, AutoCloseable { @@ -171,4 +170,4 @@ class PsqlConnection internal constructor( } override fun toUri(showPassword: Boolean): String = if (showPassword) jdbc.url else toString() -} \ No newline at end of file +} diff --git a/here-naksha-lib-psql/src/jvmMain/kotlin/naksha/psql/PsqlCursor.kt b/here-naksha-lib-psql/src/jvmMain/kotlin/naksha/psql/PsqlCursor.kt index 26a1d0208..3ca427aac 100644 --- a/here-naksha-lib-psql/src/jvmMain/kotlin/naksha/psql/PsqlCursor.kt +++ b/here-naksha-lib-psql/src/jvmMain/kotlin/naksha/psql/PsqlCursor.kt @@ -1,10 +1,7 @@ package naksha.psql import naksha.base.AnyObject -import naksha.base.Int64 import naksha.base.Platform -import naksha.base.Platform.PlatformCompanion.longToInt64 -import naksha.base.toInt64 import java.sql.ResultSet import java.sql.Statement import kotlin.reflect.KClass @@ -183,8 +180,7 @@ class PsqlCursor internal constructor(private val stmt: Statement, private val c is Byte -> result[i] = raw.toInt() is Short -> result[i] = raw.toInt() is Int -> result[i] = raw - is Long -> result[i] = raw.toInt64() - is Int64 -> result[i] = raw + is Long -> result[i] = raw is Float -> result[i] = raw.toDouble() is Double -> result[i] = raw is String -> result[i] = raw @@ -210,20 +206,20 @@ class PsqlCursor internal constructor(private val stmt: Statement, private val c } return when (type) { // TODO: We need to check which values can simply read using getObject, so we can avoid the null-casting. - // However, we want to return Integer for short and Int64 for long, so some hacks are needed, just which? + // However, we want to return Integer for short and Long for long, so some hacks are needed, just which? "null" -> null "text", "varchar", "character", "char", "json", "uuid", "inet", "cidr", "macaddr", "xml", "internal", "point", "line", "lseg", "box", "path", "polygon", "circle", "int4range", "int8range", "numrange", "tsrange", "tstzrange", "daterange" -> valueOrNull(rs, rs.getString(index)) "smallint", "int2" -> valueOrNull(rs, rs.getShort(index).toInt()) "integer", "int", "int4", "xid4", "oid" -> valueOrNull(rs, rs.getInt(index)) - "bigint", "int8", "xid8" -> valueOrNull(rs, longToInt64(rs.getLong(index))) + "bigint", "int8", "xid8" -> valueOrNull(rs, rs.getLong(index)) "real" -> valueOrNull(rs, rs.getFloat(index).toDouble()) "double precision" -> valueOrNull(rs, rs.getDouble(index)) "numeric" -> valueOrNull(rs, rs.getBigDecimal(index)) "bool", "boolean" -> valueOrNull(rs, rs.getBoolean(index)) - "timestamp" -> valueOrNull(rs, longToInt64(rs.getTimestamp(index).toInstant().toEpochMilli())) - "date" -> valueOrNull(rs, longToInt64(rs.getDate(index).toInstant().toEpochMilli())) + "timestamp" -> valueOrNull(rs, rs.getTimestamp(index).toInstant().toEpochMilli()) + "date" -> valueOrNull(rs, rs.getDate(index).toInstant().toEpochMilli()) "bytea" -> valueOrNull(rs, rs.getBytes(index)) "jsonb" -> rs.getString(index)?.let { Platform.fromJSON(it) } else -> rs.getObject(index) diff --git a/here-naksha-lib-psql/src/jvmMain/kotlin/naksha/psql/PsqlInstance.kt b/here-naksha-lib-psql/src/jvmMain/kotlin/naksha/psql/PsqlInstance.kt index 670fd28e2..96a9e2cb8 100644 --- a/here-naksha-lib-psql/src/jvmMain/kotlin/naksha/psql/PsqlInstance.kt +++ b/here-naksha-lib-psql/src/jvmMain/kotlin/naksha/psql/PsqlInstance.kt @@ -1,8 +1,6 @@ package naksha.psql -import naksha.base.Int64 import naksha.base.Platform.PlatformCompanion.logger -import naksha.base.Platform.PlatformCompanion.longToInt64 import naksha.base.fn.Fx2 import naksha.model.SessionOptions import org.postgresql.PGProperty.* @@ -68,7 +66,7 @@ class PsqlInstance(private val config: PgInstanceConfig) : PgInstance { internal data class PooledPgConnection( val jdbcConn: org.postgresql.jdbc.PgConnection, - val id: Int64 = longToInt64(connCounter.getAndIncrement()), + val id: Long = connCounter.getAndIncrement(), val idle: AtomicInteger = AtomicInteger(0), val connection: AtomicReference?> = AtomicReference(), var e: Exception? = null @@ -86,7 +84,7 @@ class PsqlInstance(private val config: PgInstanceConfig) : PgInstance { /** * All open connections (the connection pool). */ - internal val connectionPool = ConcurrentHashMap() + internal val connectionPool = ConcurrentHashMap() /** * The host specification. @@ -360,4 +358,4 @@ SET SESSION pg_hint_plan.enable_hint = on; * @return the JDBC URL of this instance with obfuscated password. */ override fun toString(): String = url -} \ No newline at end of file +} diff --git a/here-naksha-lib-psql/src/jvmMain/kotlin/naksha/psql/PsqlQuery.kt b/here-naksha-lib-psql/src/jvmMain/kotlin/naksha/psql/PsqlQuery.kt index f24e60a6e..f4bc432c0 100644 --- a/here-naksha-lib-psql/src/jvmMain/kotlin/naksha/psql/PsqlQuery.kt +++ b/here-naksha-lib-psql/src/jvmMain/kotlin/naksha/psql/PsqlQuery.kt @@ -1,7 +1,5 @@ package naksha.psql -import naksha.base.Int64 -import naksha.base.JvmInt64 import naksha.base.ListProxy import naksha.base.MapProxy import naksha.base.Platform @@ -100,7 +98,6 @@ class PsqlQuery(query: String, private val typeNames: Array?) { is Short -> for (index in indices) stmt.setShort(index, arg) is Int -> for (index in indices) stmt.setInt(index, arg) is Long -> for (index in indices) stmt.setLong(index, arg) - is Int64 -> for (index in indices) stmt.setLong(index, arg.toLong()) is Float -> for (index in indices) stmt.setFloat(index, arg) is Double -> for (index in indices) stmt.setDouble(index, arg) is String -> for (index in indices) stmt.setString(index, arg) @@ -119,26 +116,20 @@ class PsqlQuery(query: String, private val typeNames: Array?) { // https://jdbc.postgresql.org/documentation/server-prepare/#arrays var componentType = arg.javaClass.componentType!! var array: Array<*> = arg - if (componentType == Any::class.java || componentType == Int64::class.java || componentType == JvmInt64::class.java) { + if (componentType == Any::class.java) { // Special handling for `Array`: // Array of objects need to be turned either into a `java.sql.Array` or converted into a `Array`. // The reason is that the driver only accepts arrays with same content, and if the content is null, // it still needs to know the type. - // We treat Int64 as Long until we switched finally! - if (componentType == Int64::class.java || componentType == JvmInt64::class.java) { - componentType = Long::class.javaObjectType - } else for (value in arg) { + for (value in arg) { if (value == null) continue componentType = value.javaClass - if (componentType == Int64::class.java || componentType == JvmInt64::class.java) { - componentType = Long::class.javaObjectType - } break } if (componentType == Any::class.java) { // Try to detect the component type from what the client provided in the prepared statement. if (typeName != null) { - val pgType = PgType.of(typeName) + val pgType = PgType.of(typeName) ?: PgType.of(typeName.removeSuffix("[]")) if (pgType != null) { val klass: KClass<*>? = if (pgType.isArray) pgType.componentType?.klass else pgType.klass if (klass != null) componentType = klass.javaObjectType @@ -163,8 +154,7 @@ class PsqlQuery(query: String, private val typeNames: Array?) { v } Long::class.javaObjectType -> Array(array.size) { - var v = arg[it] - if (v is Int64) v = v.toLong() + val v = arg[it] if (v != null && v !is Long) throw illegalArg("Illegal value in Long array at $it: '$v'") v } diff --git a/here-naksha-lib-view/src/jvmMain/java/com/here/naksha/lib/view/ViewLayerCollection.java b/here-naksha-lib-view/src/jvmMain/java/com/here/naksha/lib/view/ViewLayerCollection.java index b1201730b..a514e06e9 100644 --- a/here-naksha-lib-view/src/jvmMain/java/com/here/naksha/lib/view/ViewLayerCollection.java +++ b/here-naksha-lib-view/src/jvmMain/java/com/here/naksha/lib/view/ViewLayerCollection.java @@ -58,7 +58,7 @@ public int priorityOf(ViewLayer layer) { public ViewLayer getByTupleNumber(@NotNull TupleNumber tupleNumber) { for (ViewLayer layer : layers) { - if (layer.getStorage().getNumber().toLong() != tupleNumber.databaseNumber.toLong()) { + if (layer.getStorage().getNumber() != tupleNumber.databaseNumber) { continue; } String mapId = layer.getMapId(); diff --git a/here-naksha-lib-view/src/jvmMain/java/com/here/naksha/lib/view/concurrent/ParallelQueryExecutor.java b/here-naksha-lib-view/src/jvmMain/java/com/here/naksha/lib/view/concurrent/ParallelQueryExecutor.java index d11739cfa..668efe2e9 100644 --- a/here-naksha-lib-view/src/jvmMain/java/com/here/naksha/lib/view/concurrent/ParallelQueryExecutor.java +++ b/here-naksha-lib-view/src/jvmMain/java/com/here/naksha/lib/view/concurrent/ParallelQueryExecutor.java @@ -20,7 +20,6 @@ import static com.here.naksha.lib.core.exceptions.UncheckedException.unchecked; import static java.util.stream.Collectors.groupingBy; -import static naksha.base.Platform.longToInt64; import static naksha.base.NakshaError.EXCEPTION; import static naksha.base.NakshaError.INTERNAL_ERROR; @@ -32,7 +31,6 @@ import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; -import naksha.base.Int64; import naksha.base.NakshaError; import naksha.base.NakshaException; import naksha.model.*; @@ -107,7 +105,7 @@ public ParallelQueryExecutor(@NotNull View view) { final @NotNull Response readResponse = session.execute(readRequest); final FeatureTupleList featureTupleList = getFeatureTuples(readResponse); - final Int64 maxMicros = longToInt64(TimeUnit.SECONDS.toMicros(10)); + final long maxMicros = TimeUnit.SECONDS.toMicros(10); Naksha.cache.load(featureTupleList, 0, featureTupleList.size(), maxMicros, true, true); log.info( "[View Request stats => streamId,layerId,method,status,timeTakenMs,fCnt] - ViewReqStats {} {} {} {} {} {}", diff --git a/here-naksha-lib-view/src/jvmTest/java/com/here/naksha/lib/view/Sample.java b/here-naksha-lib-view/src/jvmTest/java/com/here/naksha/lib/view/Sample.java index f5af3a83a..56efc0053 100644 --- a/here-naksha-lib-view/src/jvmTest/java/com/here/naksha/lib/view/Sample.java +++ b/here-naksha-lib-view/src/jvmTest/java/com/here/naksha/lib/view/Sample.java @@ -18,7 +18,6 @@ */ package com.here.naksha.lib.view; -import static naksha.base.LibBaseKt.Int64; import static naksha.model.RandomFeatures.randomFeature; import naksha.base.Action; @@ -33,7 +32,7 @@ public class Sample { public static FeatureTuple featureTuple(NakshaFeature feature) { - TupleNumber tupleNumber = new TupleNumber(Int64(1), 0, 0, Naksha.featureNumber(feature.getId()), Int64(1)); + TupleNumber tupleNumber = new TupleNumber(1L, 0, 0, Naksha.featureNumber(feature.getId()), 1L); feature.getProperties().getXyz().setRaw("uuid", tupleNumber.toString()); FeatureTuple featureTuple = new FeatureTuple(tupleNumber, (Tuple) null); featureTuple.setFeature(feature); diff --git a/here-naksha-lib-view/src/jvmTest/java/com/here/naksha/lib/view/merge/MergeByStoragePriorityTest.java b/here-naksha-lib-view/src/jvmTest/java/com/here/naksha/lib/view/merge/MergeByStoragePriorityTest.java index 4b9b8603f..cc6c3fe56 100644 --- a/here-naksha-lib-view/src/jvmTest/java/com/here/naksha/lib/view/merge/MergeByStoragePriorityTest.java +++ b/here-naksha-lib-view/src/jvmTest/java/com/here/naksha/lib/view/merge/MergeByStoragePriorityTest.java @@ -9,7 +9,6 @@ import java.util.ArrayList; import java.util.List; -import static naksha.base.LibBaseKt.Int64; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.mock; diff --git a/here-naksha-storage-http/src/jvmMain/java/com/here/naksha/storage/http/HttpStorage.java b/here-naksha-storage-http/src/jvmMain/java/com/here/naksha/storage/http/HttpStorage.java index 33817d60d..227b6d8e4 100644 --- a/here-naksha-storage-http/src/jvmMain/java/com/here/naksha/storage/http/HttpStorage.java +++ b/here-naksha-storage-http/src/jvmMain/java/com/here/naksha/storage/http/HttpStorage.java @@ -22,7 +22,6 @@ import com.here.naksha.storage.http.cache.RequestSenderCache; import kotlin.reflect.KClass; import naksha.base.Action; -import naksha.base.Int64; import naksha.base.JvmBoxingUtil; import naksha.base.Platform; import naksha.base.TupleNumber; @@ -136,7 +135,7 @@ public int getHardCap() { } @Override - public @NotNull Int64 getNumber() { + public long getNumber() { throw new NotImplementedException("Not supported by HTTP storage"); } diff --git a/here-naksha-storage-http/src/jvmMain/java/com/here/naksha/storage/http/connector/ConnectorInterfaceWriteExecute.java b/here-naksha-storage-http/src/jvmMain/java/com/here/naksha/storage/http/connector/ConnectorInterfaceWriteExecute.java index b5c4f759e..5e238d087 100644 --- a/here-naksha-storage-http/src/jvmMain/java/com/here/naksha/storage/http/connector/ConnectorInterfaceWriteExecute.java +++ b/here-naksha-storage-http/src/jvmMain/java/com/here/naksha/storage/http/connector/ConnectorInterfaceWriteExecute.java @@ -6,7 +6,6 @@ import com.here.naksha.lib.core.util.json.JsonSerializable; import com.here.naksha.storage.http.PrepareResult; import com.here.naksha.storage.http.RequestSender; -import naksha.base.Int64; import naksha.base.Platform; import naksha.model.NakshaContext; import naksha.base.NakshaError; @@ -50,11 +49,11 @@ public ConnectorInterfaceWriteExecute(NakshaContext context, WriteRequest reques this.endpoint = "/" + singleCollectionIdFrom(request); } - private static void setCreatedAt(NakshaFeature feature, Int64 creationTime) { + private static void setCreatedAt(NakshaFeature feature, long creationTime) { feature.getProperties().getXyz().setRaw("createdAt", creationTime); } - private static void setUpdatedAt(NakshaFeature feature, Int64 creationTime) { + private static void setUpdatedAt(NakshaFeature feature, long creationTime) { feature.getProperties().getXyz().setRaw("updatedAt", creationTime); } @@ -103,7 +102,7 @@ private ModifyFeaturesEvent createModifyFeaturesEvent() { } } - Int64 currentTime = Platform.currentMillis(); + long currentTime = Platform.currentMillis(); featuresToInsert.forEach(feature -> { assertNoUuid(feature); setRandomUuid(feature); From 1085a0e22db0915ac4e380850897f15abcb5aaa7 Mon Sep 17 00:00:00 2001 From: Alexander Lowey-Weber Date: Mon, 31 Aug 2026 13:47:57 +0200 Subject: [PATCH 24/41] Improve PgRows to supports arrays and consistent resize, fix failing tests. Signed-off-by: Alexander Lowey-Weber --- .../commonMain/kotlin/naksha/model/TagList.kt | 41 ++++++-- .../commonMain/kotlin/naksha/model/Tuple.kt | 9 +- .../kotlin/naksha/psql/PgColumnWithValues.kt | 55 +++++++++-- .../kotlin/naksha/psql/PgQueryWhereBuilder.kt | 8 +- .../commonMain/kotlin/naksha/psql/PgRows.kt | 95 ++++++++++--------- .../kotlin/naksha/psql/PgWriterBase.kt | 4 +- .../kotlin/naksha/psql/PgWriterDelete.kt | 4 +- .../kotlin/naksha/psql/PgWriterUpdate.kt | 2 +- .../kotlin/naksha/psql/DeleteFeatureBase.kt | 7 +- .../kotlin/naksha/psql/PgRowsTest.kt | 41 ++++++++ .../naksha/psql/ReadFeaturesByTagMapTest.kt | 11 +-- 11 files changed, 195 insertions(+), 82 deletions(-) create mode 100644 here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/PgRowsTest.kt diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TagList.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TagList.kt index 75750641f..84649d13a 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TagList.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TagList.kt @@ -4,6 +4,7 @@ package naksha.model import naksha.base.ITagList import naksha.base.StringList +import naksha.base.illegalArg import naksha.model.TagNormalizer.TagNormalizer_C.normalizeTag import kotlin.js.JsExport import kotlin.js.JsName @@ -20,10 +21,32 @@ class TagList() : StringList(), ITagList { /** * Create a tag list from the given arguments; the tags are normalized. * @param tags the tags. + * @param skipNormalize if normalization should be skipped; expects then that the given values are already normalized. */ + @JvmOverloads @JsName("of") - constructor(vararg tags: String): this() { - addTags(listOf(*tags), false) + constructor(vararg tags: String, skipNormalize: Boolean = false): this() { + setCapacity(tags.size) + for (tag in tags) addTag(tag, !skipNormalize) + } + + /** + * Create a tag list from the given list; the tags are normalized. + * @param tags the tags. + * @param skipInvalid if invalid values in the given should be skipped; otherwise an exception is raised. + * @param skipNormalize if normalization should be skipped; expects then that the given values are already normalized. + * @throws naksha.base.NakshaException with error [ILLEGAL_ARGUMENT][naksha.base.NakshaError.ILLEGAL_ARGUMENT] if the given list contains `null` or valus not being `String` and [skipInvalid] is _false_. + */ + @JvmOverloads + @JsName("ofList") + constructor(tags: List<*>, skipInvalid: Boolean = false, skipNormalize: Boolean = false): this() { + setCapacity(tags.size) + for (i in 0 until tags.size) { + val tag = tags[i] + if (tag is String) addTag(tag, skipInvalid) + else if (tag is Char || tag is CharSequence) addTag(tag.toString(), !skipNormalize) + else if (!skipInvalid) throw illegalArg("The tag $i is no string: $tag") + } } /** @@ -159,18 +182,22 @@ class TagList() : StringList(), ITagList { /** * Create a tag list from the given array. Values being `null` or no [String] are ignored. * @param tags the tags. - * @param normalize if the values should be normalized. + * @param skipInvalid if invalid values in the given should be skipped; otherwise an exception is raised. + * @param skipNormalize if normalization should be skipped; expects then that the given values are already normalized. + * @throws naksha.base.NakshaException with error [ILLEGAL_ARGUMENT][naksha.base.NakshaError.ILLEGAL_ARGUMENT] if the given list contains `null` or valus not being `String` and [skipInvalid] is _false_. * @return the tag-list. * @since 3.0 */ @JvmStatic @JsStatic @JvmOverloads - fun fromArray(tags: Array<*>, normalize: Boolean = true): TagList = TagList().apply { + fun fromArray(tags: Array<*>, skipInvalid: Boolean = false, skipNormalize: Boolean = false): TagList = TagList().apply { setCapacity(tags.size) - for (tag in tags) { - if (tag is String) addTag(tag, normalize) - else if (tag is Char || tag is CharSequence) addTag(tag.toString(), normalize) + for (i in 0 until tags.size) { + val tag = tags[i] + if (tag is String) addTag(tag, !skipNormalize) + else if (tag is Char || tag is CharSequence) addTag(tag.toString(), !skipNormalize) + else if (!skipInvalid) throw illegalArg("The tag #$i is no string: $tag") } } diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/Tuple.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/Tuple.kt index 6304b3911..2c0c46e4d 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/Tuple.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/Tuple.kt @@ -234,7 +234,7 @@ data class Tuple @JvmOverloads constructor( TN -> newTn NEXT_VERSION -> null ORIGIN -> origin - GLOBAL_BOOK_FN -> globalBookTn?.featureNumber?.toLong() + GLOBAL_BOOK_FN -> globalBookTn?.featureNumber CHANGE_COUNT -> (member.readLong(f) ?: 0L) + 1L else -> member.read(f) } @@ -511,10 +511,9 @@ data class Tuple @JvmOverloads constructor( private fun coerceTagList(value: Any, featureId: String, memberName: String): TagList? { val list = when (value) { is TagList -> value - is Array<*> -> TagList().apply { - setCapacity(value.size) - for (v in value) if (v is String) addTag(v, true) - } + is PlatformList -> value.proxy(TagList::class) + is Array<*> -> TagList.fromArray(value) + is List<*> -> TagList(value) else -> value.proxy(TagList::class) } if (list != null) return list diff --git a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgColumnWithValues.kt b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgColumnWithValues.kt index 9cba9cd26..f88ac5c1c 100644 --- a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgColumnWithValues.kt +++ b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgColumnWithValues.kt @@ -1,15 +1,28 @@ package naksha.psql -import naksha.base.AnyList import naksha.base.Platform.PlatformCompanion.toJSON +import naksha.base.illegalArg import naksha.model.objects.MemberType +import kotlin.math.max /** * Rows as selected in [PgRows]. * @since 3.0 */ -@Suppress("UNCHECKED_CAST") +@Suppress("UNCHECKED_CAST", "ArrayInDataClass") internal data class PgColumnWithValues( + /** + * The [PgRows] to which this is bound. + * @since 3.0 + */ + val pgRows: PgRows, + + /** + * The index in [PgRows.columns]. + * @since 3.0 + */ + val index: Int, + /** * The database column. * @since 3.0 @@ -26,18 +39,46 @@ internal data class PgColumnWithValues( * The values of the column for each row. * @since 3.0 */ - val values: AnyList = AnyList() + internal var values: Array = arrayOfNulls(pgRows.size), ) { - fun withSize(size: Int): PgColumnWithValues { - values.size = size - return this + + /** + * The size of the [values], so amount of row values for this column. + * @since 3.0 + */ + var size: Int + get() = pgRows.size + set(value) { + pgRows.size = value + } + + /** + * Returns the value from the given index or `null`. + * @param i the index to query. + * @return the value at the given index or `null`. + * @since 3.0 + */ + operator fun get(i: Int) = if (i in 0 until size) values[i] else null + + /** + * Sets the value at the given index. If the current [size] is less than `i`, increases the size, potentially adding `null` values. + * @param i the index to set. + * @param value the value to set. + * @throws naksha.base.NakshaException with error [ILLEGAL_ARGUMENT][naksha.base.NakshaError.ILLEGAL_ARGUMENT] if the given index `i` is less than zero. + * @since 3.0 + */ + operator fun set(i: Int, value: Any?) { + if (i < 0) throw illegalArg("The given index $i is less than zero") + if (i >= size) size = i + 1 + values[i] = value } + /** * Returns all values of this column as array that can be feed into PostgresQL [UNNEST](https://www.postgresql.org/docs/18/functions-array.html) function. Requires a minor hack for [naksha.model.TagList]. * @see PgRows.setRow * @see PgRows.values */ - fun toArray(): Array = Array(values.size) { + fun toArray(): Array = Array(size) { val value = values[it] when (pgColumn.memberType) { // We keep it internally as text[], but UNNEST requires only one value. diff --git a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgQueryWhereBuilder.kt b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgQueryWhereBuilder.kt index 9da6c68b9..67f78cdc8 100644 --- a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgQueryWhereBuilder.kt +++ b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgQueryWhereBuilder.kt @@ -354,7 +354,7 @@ internal class PgQueryWhereBuilder(private val request: ReadFeatures, private va // Do any of the strings in the text array exist as top-level keys or array elements? // '{"a":1, "b":2, "c":3}'::jsonb ?| array['b', 'd'] → t if (negate) where.append("NOT ") - where.append(memberName).append(" ??| ").append(_keys_array_).append(" ") + where.append(memberName).append(" ??| ").append(_keys_array_).append("::text[] ") } private fun _TagMapHasAllOf(negate: Boolean, memberName: String, keys: StringList) { @@ -365,7 +365,7 @@ internal class PgQueryWhereBuilder(private val request: ReadFeatures, private va // Do all of the strings in the text array exist as top-level keys or array elements? // '["a", "b", "c"]'::jsonb ?& array['a', 'b'] → t if (negate) where.append("NOT ") - where.append(memberName).append(" ??& ").append(_keys_array_).append(" ") + where.append(memberName).append(" ??& ").append(_keys_array_).append("::text[] ") } private fun _TagIsNull(negate: Boolean, memberName: String, key: String) { @@ -511,14 +511,14 @@ internal class PgQueryWhereBuilder(private val request: ReadFeatures, private va */ private fun evaluateJsonPath(memberName: String, key: String, expression: String) { val _jsonpath_ = placeholderForArg( - "$.${quoteString(key)} ?? ($expression)", + "$.${quoteString(key)} ? ($expression)", PgType.STRING ) // jsonb @? jsonpath → boolean // Does JSON path return any item for the specified JSON value? // '{"a":5}'::jsonb @? '$.a ? (@ > 2)' → t // '{"a":[1,2,3,4,5]}'::jsonb @? '$.a[*] ? (@ > 2)' → t - where.append(memberName).append(" @?? ").append(_jsonpath_) + where.append(memberName).append(" @?? ").append(_jsonpath_).append("::jsonpath ") } /** diff --git a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgRows.kt b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgRows.kt index d66ac7e4b..4955cef22 100644 --- a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgRows.kt +++ b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgRows.kt @@ -12,6 +12,7 @@ import naksha.base.Platform.PlatformCompanion.toJSON import naksha.base.TupleNumber import naksha.model.objects.MemberType import naksha.base.Version +import naksha.base.illegalArg import naksha.base.internalError import naksha.base.proxy import naksha.geo.GeoUtil @@ -32,6 +33,7 @@ import naksha.model.objects.StandardMembers.StandardMembers_C.FeatureBytes import naksha.model.objects.StandardMembers.StandardMembers_C.Id import naksha.model.objects.StandardMembers.StandardMembers_C.NextVersion import naksha.model.objects.StandardMembers.StandardMembers_C.Tn +import kotlin.math.max /** * Helper class to convert rows into arrays of column-data and vice versa. @@ -63,22 +65,31 @@ internal class PgRows { */ var size: Int = 0 set(value) { - if (field != value) { - for (column in columns) { - column.values.size = value - } + if (value > field) withMinCapacity(value) + field = max(0, value) + } + + /** + * The capacity of the columns, can't shrink. + * @since 3.0 + */ + var capacity: Int = 0 + set (value) { + if (value > field) { + val new_capacity = max(4, (value * 1.25).toInt()) + for (column in columns) column.values = column.values.copyOf(new_capacity) field = value } } /** - * Ensures that all columns have at least this amount of values, if too short, adds `null` values until the minimal size is reached. + * Ensures that all columns have minimally this capacity. + * @param minCapacity the minimal amount of rows, so minimal size of each column values. + * @return this. * @since 3.0 */ - fun setMinRows(rowsCount: Int): PgRows { - if (this.size < rowsCount) { - this.size = rowsCount - } + fun withMinCapacity(minCapacity: Int): PgRows { + if (capacity < minCapacity) capacity = minCapacity return this } @@ -95,7 +106,7 @@ internal class PgRows { catalogNumber = collection.catalog.catalogNumber databaseNumber = collection.catalog.storage.number for (pgColumn in collection.columns) { - columns.add(PgColumnWithValues(pgColumn)) + columns.add(PgColumnWithValues(this, this.columns.size, pgColumn)) } } field = collection @@ -173,7 +184,7 @@ internal class PgRows { val alias = column.name val existing = getColumn(alias) if (existing != null) continue - this.columns.add(PgColumnWithValues(column, alias).withSize(size)) + this.columns.add(PgColumnWithValues(this, this.columns.size, column, alias)) } return this } @@ -182,8 +193,7 @@ internal class PgRows { clearCache() val existing = getColumn(alias) if (existing == null) { - val column = PgColumnWithValues(column, alias).withSize(size) - columns.add(column) + columns.add(PgColumnWithValues(this, this.columns.size, column, alias)) } return this } @@ -191,8 +201,8 @@ internal class PgRows { clearCache() val existing = getColumn(alias) if (existing == null) { - val column = PgColumnWithValues(PgColumn(-1, alias, type)).withSize(size) - columns.add(column) + val pgColumn = PgColumn(-1, alias, type) + columns.add(PgColumnWithValues(this, this.columns.size, pgColumn)) } return this } @@ -206,7 +216,7 @@ internal class PgRows { fun hasColumn(index: Int): Boolean = getColumn(index) != null - fun getAny(row: Int, alias: String): Any? = getColumn(alias)?.values?.get(row) + fun getAny(row: Int, alias: String): Any? = getColumn(alias)?.get(row) fun getAny(row: Int, column: PgColumn): Any? = getAny(row, column.name) fun getInt(row: Int, alias: String): Int? = getAny(row, alias) as? Int fun getInt(row: Int, column: PgColumn): Int? = getInt(row, column.name) @@ -242,14 +252,8 @@ internal class PgRows { // Stored as text[], therefore returned by JDBC as Array. val raw = getArray(row, alias) ?: return null return try { - val tagList = TagList() - tagList.setCapacity(raw.size) - for (tag in raw) { - if (tag !is String) continue - // We know that we read back data we serialized, tags are normalized! - tagList.addTag(tag, false) - } - tagList + // We know that we read back data we serialized, tags are normalized! + TagList.fromArray(raw, skipInvalid = true, skipNormalize = true) } catch (_: Exception) { null } @@ -296,7 +300,7 @@ internal class PgRows { val member = members[i] ?: continue val name = member.name if (name == FeatureBytes.name) { - val value = getColumn(name)?.values?.get(row) + val value = getAny(row, name) if (value !is ByteArray) throw NakshaException(ILLEGAL_STATE, "The feature root is no byte-array") featureBytes = value continue @@ -304,19 +308,18 @@ internal class PgRows { if (member.isVirtual()) continue when (name) { Tn.name -> { - val fn = getColumn(PgColumn.FnColumn.name)?.values?.get(row) as? Long - val ver = getColumn(PgColumn.VersionColumn.name)?.values?.get(row) as? Long + val fn = getLong(row, PgColumn.FnColumn) + val ver = getLong(row, PgColumn.VersionColumn) val db = databaseNumber; val cat = catalogNumber; val col = collectionNumber val tn = if (fn != null && ver != null && db != null && cat != null && col != null) TupleNumber(db, cat, col, fn, ver) else null membersBook.put(name, tn) } NextVersion.name -> { - val raw = getColumn(name)?.values?.get(row) as? Long - membersBook.put(name, raw ?: Version.HEAD.number) + membersBook.put(name, getLong(row, name) ?: Version.HEAD.number) } else -> { - val pg_value = getColumn(name)?.values?.get(row) + val pg_value = getAny(row, name) val value = member.dataType.convert(pg_value) membersBook.put(name, value) } @@ -341,11 +344,12 @@ internal class PgRows { // TODO: The current usage luckily avoids setting structured types with special encoding. // However, theoretically we need to handle TagMap and TagList! - fun setColumn(row: Int, columnName: String, value: Any?): Boolean { + fun setColumn(columnName: String, row: Int, value: Any?): Boolean { val column = getColumn(columnName) if (column != null) { - setMinRows(row+1) - column.values[row] = if (SPATIAL == column.pgColumn.memberType) GeoUtil.toTWKB(value as SpGeometry?) else value + withMinCapacity(row + 1) + val memberType = column.pgColumn.memberType + column[row] = if (SPATIAL == memberType && value is SpGeometry) GeoUtil.toTWKB(value) else value return true } return false @@ -354,20 +358,21 @@ internal class PgRows { operator fun set(row: Int, tuple: Tuple) = setRow(row, tuple) fun setRow(row: Int, tuple: Tuple) { - setMinRows(row+1) + withMinCapacity(row+1) val membersBook = tuple.membersBook val END = membersBook.namesLength() for (i in 0 until END) { val memberName = membersBook.getNameAt(i) ?: continue val column = getColumn(memberName) ?: continue + val memberType = column.pgColumn.memberType val member_value = membersBook[memberName] // Note: The members book is required to contain correctly typed values. // We convert these values into what is stored in PostgresQL. - column.values[row] = when (val member_type = column.pgColumn.memberType) { + val pg_value = when (memberType) { BOOLEAN -> member_value as? Boolean INT8 -> member_value as? Byte INT16 -> member_value as? Short - INT32 -> member_value as? Byte + INT32 -> member_value as? Int INT64 -> member_value as? Long FLOAT32 -> member_value as? Float FLOAT64 -> member_value as? Double @@ -381,21 +386,22 @@ internal class PgRows { TAG_MAP -> if (member_value is TagMap) toJSON(member_value) else null // Stored as text[] TAG_LIST -> if (member_value is TagList) member_value.toStringArray(true) else null - else -> throw internalError("PgRows: Unknown member type in member book: $member_type") + else -> throw internalError("PgRows: Unknown member type in member book: $memberType") } + column[row] = pg_value } // The members-book keeps the tuple-number as a single `_tn` entry; the table splits it into the // `_fn` and `_version` columns, so populate those from the tuple-number. val tn = tuple.tupleNumber - getColumn(PgColumn.FnColumn.name)?.let { it.values[row] = tn.featureNumber } - getColumn(PgColumn.VersionColumn.name)?.let { it.values[row] = tn.version } + getColumn(PgColumn.FnColumn.name)?.let { it[row] = tn.featureNumber } + getColumn(PgColumn.VersionColumn.name)?.let { it[row] = tn.version } // HEAD rows store next_version as NULL; translate the encoder's HEAD sentinel into NULL. - getColumn(PgColumn.NextVersionColumn.name)?.let { if (it.values[row] == Version.HEAD.number) it.values[row] = null } + getColumn(PgColumn.NextVersionColumn.name)?.let { if (it[row] == Version.HEAD.number) it[row] = null } // `_id` is materialized only when it is not derivable from the feature-number: fn < 0 => hashed // id, fn >= 0 => id equals fn so `_id` stays NULL (a CHECK enforces both cases). - getColumn(Id.name)?.let { it.values[row] = if (tn.featureNumber < 0L) membersBook[Id.name] else null } + getColumn(Id.name)?.let { it[row] = if (tn.featureNumber < 0L) membersBook[Id.name] else null } val featureColumn = getColumn(FeatureBytes.name) ?: return - featureColumn.values[row] = tuple.featureBytes + featureColumn[row] = tuple.featureBytes } /** @@ -406,13 +412,12 @@ internal class PgRows { */ operator fun set(row: Int, cursor: PgCursor) { if (!cursor.isRow()) return - // Grow to hold index `row` (size must be row + 1) so appended read rows are retained. - setMinRows(row + 1) + withMinCapacity(row + 1) val columnNames = cursor.columnNames() for (columnName in columnNames) { val column = getColumn(columnName) ?: continue val value = cursor.column(columnName) - column.values[row] = value + column[row] = value } } diff --git a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgWriterBase.kt b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgWriterBase.kt index 6a4768b52..a5da7ae7a 100644 --- a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgWriterBase.kt +++ b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgWriterBase.kt @@ -159,8 +159,8 @@ internal abstract class PgWriterBase protected constructor( * @return the number of rows loaded. */ protected fun loadAllTuple(lambda: Fx3? = null): Int { - var row = 0 - inRows.setMinRows(inRows.size + (end - start)) + var row = inRows.size + inRows.withMinCapacity(inRows.size + (end - start)) for (i in start ..< end) { val pgWrite = pgWrites[i] val tuple = pgWrite.tuple ?: throw illegalArg("The write #$i has no tuple, failed to load all tuple") diff --git a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgWriterDelete.kt b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgWriterDelete.kt index 29d1be7d8..9ff4bd632 100644 --- a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgWriterDelete.kt +++ b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgWriterDelete.kt @@ -42,8 +42,8 @@ internal class PgWriterDelete( var row = 0 for (i in start until end) { val pgWrite = pgWrites[i] - inRows.setColumn(row, FnColumn.ident, pgWrite.featureNumber) - inRows.setColumn(row, "expected_version", pgWrite.version?.number) + inRows.setColumn(FnColumn.ident, row, pgWrite.featureNumber) + inRows.setColumn("expected_version", row, pgWrite.version?.number) row++ } check(row == (end-start)) diff --git a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgWriterUpdate.kt b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgWriterUpdate.kt index bbc3ba29c..f9dc8cae5 100644 --- a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgWriterUpdate.kt +++ b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgWriterUpdate.kt @@ -37,7 +37,7 @@ internal class PgWriterUpdate( loadAllTuple { row, tuple, pgWrite -> writeByFn[tuple.tupleNumber.featureNumber] = pgWrite // Separate column for the expected HEAD version. - inRows.setColumn(row, "expected_version", pgWrite.version?.number) + inRows.setColumn("expected_version", row, pgWrite.version?.number) } } diff --git a/here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/DeleteFeatureBase.kt b/here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/DeleteFeatureBase.kt index a8c58d9e4..b411062e6 100644 --- a/here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/DeleteFeatureBase.kt +++ b/here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/DeleteFeatureBase.kt @@ -154,9 +154,10 @@ abstract class DeleteFeatureBase( @Test fun deleteWithoutHistoryButWithShadow() { // Create special test collection. + val collectionId = "${defaultName}_no_history_shadow" val createCollectionReq = WriteRequest().add( Write().createCollection( - NakshaCollection("delete_no_history_but_shadow", catalog.id) + NakshaCollection(collectionId, catalog.id) .withStoreDeleted(StoreMode.ON) .withStoreMeta(StoreMode.OFF) .withStoreHistory(StoreMode.OFF) @@ -167,7 +168,7 @@ abstract class DeleteFeatureBase( assertEquals(1, createCollectionResp.features.size) val collection = assertNotNull(createCollectionResp.features[0]).proxy(NakshaCollection::class) assertEquals(catalog.id, collection.catalogId) - assertEquals("delete_no_history_but_shadow", collection.id) + assertEquals(collectionId, collection.id) // Create feature. val featureId = "feature_to_delete_without_history" @@ -193,7 +194,7 @@ abstract class DeleteFeatureBase( @Test fun writeRequestWithTwoWritesDifferentCollectionsExecutedCorrectly() { //create another collection - val otherCollectionId = "delete_two_collections" + val otherCollectionId = "${defaultName}_two_collections" val createCollectionReq = WriteRequest().add(Write().createCollection(NakshaCollection(otherCollectionId, catalog.id))) val createCollectionResp = diff --git a/here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/PgRowsTest.kt b/here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/PgRowsTest.kt new file mode 100644 index 000000000..0df1c0a0d --- /dev/null +++ b/here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/PgRowsTest.kt @@ -0,0 +1,41 @@ +package naksha.psql + +import naksha.model.objects.MemberType +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlin.test.assertTrue + +class PgRowsTest { + @Test + fun shouldGrowRowsAndRetainValues() { + val rows = PgRows() + .addColumn("name", MemberType.STRING) + .addColumn("count", MemberType.INT32) + + assertEquals(0, rows.size) + assertEquals(0, rows.capacity) + + assertTrue(rows.setColumn("name", 0, "first")) + assertTrue(rows.setColumn("count", 0, 1)) + assertEquals(1, rows.size) + assertTrue(rows.capacity >= rows.size) + + assertTrue(rows.setColumn("name", 5, "sixth")) + assertTrue(rows.setColumn("count", 5, 6)) + assertEquals(6, rows.size) + assertTrue(rows.capacity >= rows.size) + assertEquals("first", rows.getString(0, "name")) + assertEquals(1, rows.getInt(0, "count")) + assertNull(rows.getAny(1, "name")) + assertEquals("sixth", rows.getString(5, "name")) + assertEquals(6, rows.getInt(5, "count")) + + val capacity = rows.capacity + rows.size = 2 + assertEquals(2, rows.size) + assertEquals(capacity, rows.capacity) + assertNull(rows.getAny(5, "name")) + assertEquals("first", rows.getString(0, "name")) + } +} diff --git a/here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/ReadFeaturesByTagMapTest.kt b/here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/ReadFeaturesByTagMapTest.kt index 48a614d58..55369540b 100644 --- a/here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/ReadFeaturesByTagMapTest.kt +++ b/here-naksha-lib-psql/src/commonTest/kotlin/naksha/psql/ReadFeaturesByTagMapTest.kt @@ -1,6 +1,5 @@ package naksha.psql -import naksha.model.Naksha import naksha.model.RandomFeatures import naksha.model.TagMap import naksha.model.objects.Index @@ -163,11 +162,11 @@ class ReadFeaturesByTagMapTest : PgTestBase( other.id, missing.id, ) - assertReturnedIds( - And(TagMapHasKey(SEARCH_TAGS_MEMBER, "negation_scope"), Not(TagGt(SEARCH_TAGS_MEMBER, "negation_number", 5))), - other.id, - missing.id, - ) + // Note: When a tag does not exist, we treat its value as NaN or NULL and by definition that never matches anything. + assertReturnedIds(And( + TagMapHasKey(SEARCH_TAGS_MEMBER, "negation_scope"), + Not(TagGt(SEARCH_TAGS_MEMBER, "negation_number", 5) + )), other.id) } @Test From 418f273903a3d4c9d27b70425669b58f20f6c7c0 Mon Sep 17 00:00:00 2001 From: Alexander Lowey-Weber Date: Mon, 31 Aug 2026 16:30:24 +0200 Subject: [PATCH 25/41] Fix that the name of an operation can be deducted from the instance type. Signed-off-by: Alexander Lowey-Weber --- .../kotlin/naksha/model/request/ops/Op.kt | 36 +++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/ops/Op.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/ops/Op.kt index 632c8a0f8..fcbc83fcb 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/ops/Op.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/request/ops/Op.kt @@ -50,7 +50,37 @@ import kotlin.jvm.JvmStatic open class Op : AnyObject() { companion object MemberOp_C { private val OP_STRING = NotNullProperty(String::class) { self, name -> - throw illegalArg("Missing '$name' property or no valid string: ${toJSON(self)}") + when (self) { + is And -> AND + is Or -> OR + is Not -> NOT + is IsNull -> IS_NULL + is IsTrue -> IS_TRUE + is IsFalse -> IS_FALSE + is Equals -> EQ + is Gt -> GT + is Gte -> GTE + is Lt -> LT + is Lte -> LTE + is StartsWith -> STARTS_WITH + is IsAnyOf -> IS_ANY_OF + is Intersects -> INTERSECTS + is TagMapHasKey -> TAGMAP_HAS_KEY + is TagMapHasAnyOf -> TAGMAP_HAS_ANY_OF + is TagMapHasAllOf -> TAGMAP_HAS_ALL_OF + is TagIsNull -> TAG_IS_NULL + is TagEquals -> TAG_EQ + is TagGt -> TAG_GT + is TagGte -> TAG_GTE + is TagLt -> TAG_LT + is TagLte -> TAG_LTE + is TagStartsWith -> TAG_STARTS_WITH + is TagMatches -> TAG_MATCHES + is TagListContains -> TAGLIST_CONTAINS + is TagListContainsAnyOf -> TAGLIST_CONTAINS_ANY_OF + is TagListContainsAllOf -> TAGLIST_CONTAINS_ALL_OF + else -> throw illegalArg("Missing '$name' property or no valid string: ${toJSON(self)}") + } } private val STRING_OR_NULL = NullableProperty(String::class) @@ -98,6 +128,8 @@ open class Op : AnyObject() { fun detect(op: Any?): Op { val realOp = op as? Op? ?: op.proxy(Op::class) ?: throw illegalArg("The given operation is not detectable: ${toJSON(op)}") + // If op is already a concrete type. + if (realOp::class !== Op::class) return realOp val opName = realOp.op val opProxy = when(opName) { AND -> op as? And ?: op.proxy(And::class) @@ -145,4 +177,4 @@ open class Op : AnyObject() { * The name of the member to query; if any _(some operations do not work upon members)_. */ var at: String? by STRING_OR_NULL -} \ No newline at end of file +} From 42d4d087fbfb368a46c18e92c9857d65d310c700 Mon Sep 17 00:00:00 2001 From: Alexander Lowey-Weber Date: Mon, 31 Aug 2026 16:31:04 +0200 Subject: [PATCH 26/41] Fix brackets in query builder and where builder. Signed-off-by: Alexander Lowey-Weber --- .../kotlin/naksha/psql/PgQueryBuilder.kt | 24 +- .../kotlin/naksha/psql/PgQueryWhereBuilder.kt | 592 +++--------------- 2 files changed, 97 insertions(+), 519 deletions(-) diff --git a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgQueryBuilder.kt b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgQueryBuilder.kt index 503cfa905..a4e1a8cdd 100644 --- a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgQueryBuilder.kt +++ b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgQueryBuilder.kt @@ -83,24 +83,24 @@ class PgQueryBuilder(val session: PgSession, val readRequest: ReadRequest) { if (version == Version.HEAD.number) { version = null // HEAD } else { - if (WHERE.isNotEmpty()) WHERE.append(" AND ") - WHERE.append("($VERSION <= ").append(version).append(")") + if (WHERE.isNotEmpty()) WHERE.append("AND ") + WHERE.append("($VERSION <= ").append(version).append(") ") } } var minVersion = req.minVersion if (minVersion != null) { minVersion = minVersion or 3L - if (WHERE.isNotEmpty()) WHERE.append(" AND ") - WHERE.append("($VERSION >= ").append(minVersion).append(")") + if (WHERE.isNotEmpty()) WHERE.append("AND ") + WHERE.append("($VERSION >= ").append(minVersion).append(") ") } val readHistory = req.queryHistory && pgCollection.storeHistory val versions = req.versions if (readHistory && versions == 1 && version != null) { // Return latest version only, but involve history. - if (WHERE.isNotEmpty()) WHERE.append(" AND ") + if (WHERE.isNotEmpty()) WHERE.append("AND ") WHERE.append("($NEXT_VERSION > ").append(version).append(" OR $NEXT_VERSION IS NULL) ") } if (whereQuery.isNotEmpty()) { - if (WHERE.isNotEmpty()) WHERE.append(" AND ") + if (WHERE.isNotEmpty()) WHERE.append("AND ") WHERE.append(whereQuery) } val where = if (WHERE.isEmpty()) "" else " WHERE $WHERE" @@ -108,7 +108,7 @@ class PgQueryBuilder(val session: PgSession, val readRequest: ReadRequest) { val headWhere = if (req.queryDeleted) where else { val hw = StringBuilder(WHERE) if (hw.isNotEmpty()) hw.append(" AND ") - hw.append("($VERSION & 3) < 2 ") + hw.append("(($VERSION & 3) < 2)") " WHERE $hw" } @@ -117,11 +117,11 @@ class PgQueryBuilder(val session: PgSession, val readRequest: ReadRequest) { val selectCols = (baseCols + extraCols).joinToString(", ") // The query starts with select all tuple-numbers of matching tuple. - val query = if (readHistory) """query AS -( SELECT $selectCols FROM ${pgCatalog.quotedId}.${pgCollection.headTable.quotedName}$headWhere - UNION ALL - SELECT $selectCols FROM ${pgCatalog.quotedId}.${pgCollection.historyTable.quotedName}$where )""" else """query AS -( SELECT $selectCols FROM ${pgCatalog.quotedId}.${pgCollection.headTable.quotedName}$headWhere )""" + val query = if (readHistory) """query AS ( +(SELECT $selectCols FROM ${pgCatalog.quotedId}.${pgCollection.headTable.quotedName}$headWhere) +UNION ALL +(SELECT $selectCols FROM ${pgCatalog.quotedId}.${pgCollection.historyTable.quotedName}$where) +)""" else """query AS (SELECT $selectCols FROM ${pgCatalog.quotedId}.${pgCollection.headTable.quotedName}$headWhere)""" // If history is queried, and only a certain amount of versions should be returned, // or we want only the latest version, but no specific version target is given, then diff --git a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgQueryWhereBuilder.kt b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgQueryWhereBuilder.kt index 67f78cdc8..88cccdfc0 100644 --- a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgQueryWhereBuilder.kt +++ b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgQueryWhereBuilder.kt @@ -63,14 +63,19 @@ internal class PgQueryWhereBuilder(private val request: ReadFeatures, private va if (op == null) { // When no `queryMembers` is given, we apply backward compatibility. op = QueryConverter.convert(request.query) - if (op == null && request.featureIds.isEmpty() && request.guids.isEmpty()) return null - if (request.featureIds.isNotEmpty()) whereFeatureId() - if (request.guids.isNotEmpty()) whereGuids() + if (request.featureIds.isNotEmpty()) { + val ids = request.featureIds.toStringArray(true) + if (ids.isNotEmpty()) { + op = if (op != null) And(op, IsAnyOf(Id, *ids)) else IsAnyOf(Id, *ids) + } + } + if (op == null && request.guids.isEmpty()) return null if (op != null) applyOp(op) + if (request.guids.isNotEmpty()) whereGuids() // Evil hack as there is no translations! } else { // ReadFeatures clearly states that you have to use either the new syntax or the old, not mix them! // Note: We want to get people to switch to new syntax, not start improving old queries with new features! - if (request.query.isNotEmpty()) + if (!request.query.hasNoConditions()) throw illegalArg("Old 'query' option must not be combined with new 'queryMember'") if (request.featureIds.isNotEmpty()) throw illegalArg("Old 'featureIds' option must not be combined with new 'queryMember'") @@ -99,15 +104,15 @@ internal class PgQueryWhereBuilder(private val request: ReadFeatures, private va * * The method treats a `null` value as always valid, it is up to the caller to decide if `null` is acceptable in the concrete situation. * @param memberName the name of the member. - * @param opName the name of the operation to perform. + * @param op the operation to perform. * @param value the value to test. * @param memberType the data-type of the member, which much match that of the given value. * @return the real column name to query and the real valid value to query against. * @throws NakshaException if the given value is not of the desired member-type. */ - private fun columnAndValue(memberName: String, opName: String, value: Any?, memberType: MemberType): Pair { + private fun columnAndValue(memberName: String, op: Op, value: Any?, memberType: MemberType): Pair { if (value != null && !memberType.isInstance(value)) { - throw illegalArg("The value for '$memberName' $opName '$value' is not the correct type, excepted: $memberType") + throw illegalArg("The value for '$memberName' ${op.op} '$value' is not the correct type, excepted: $memberType") } return if (memberName == Id.name) { val numeric = featureNumberAsLong(value as String) @@ -122,30 +127,31 @@ internal class PgQueryWhereBuilder(private val request: ReadFeatures, private va * @since 3.0 */ private fun applyOp(rawOp: Op, negate: Boolean = false) { - val opName = rawOp.getRaw("op") as? String? ?: throw illegalArg("Unknown operation, 'op' property is no string") val op = Op.detect(rawOp) when (op) { is And -> { - if (negate) where.append(" NOT ") val children = op.children + if (children.isEmpty()) return + if (negate) where.append("NOT ") if (children.size > 1) where.append('(') var first = true for (child in children) { if (child == null) continue - if (first) first = false else where.append(" AND ") + if (first) first = false else where.append("AND ") applyOp(child) } if (children.size > 1) where.append(") ") else where.append(" ") return } is Or -> { - if (negate) where.append(" NOT ") val children = op.children + if (children.isEmpty()) return + if (negate) where.append("NOT ") if (children.size > 1) where.append('(') var first = true for (child in children) { if (child == null) continue - if (first) first = false else where.append(" OR ") + if (first) first = false else where.append("OR ") applyOp(child) } if (children.size > 1) where.append(") ") else where.append(" ") @@ -156,7 +162,7 @@ internal class PgQueryWhereBuilder(private val request: ReadFeatures, private va return } } - val memberName: String = op.at ?: throw illegalArg("Missing 'at' (member name) for operation '$opName'") + val memberName: String = op.at ?: throw illegalArg("Missing 'at' (member name) for operation '${op.op}'") val memberType = collection.column(memberName)?.memberType ?: when (memberName) { Action.name -> MemberType.INT32 FeatureVersion.name -> MemberType.INT64 @@ -165,16 +171,16 @@ internal class PgQueryWhereBuilder(private val request: ReadFeatures, private va else -> throw illegalArg("PgQueryWhereBuilder: Unknown member '$memberName' in collection '${collection.id}'") } when (op) { - is IsNull -> _IsNull(negate, memberName, opName, memberType) - is IsTrue -> _IsTrue(negate, memberName, opName, memberType) - is IsFalse -> _IsFalse(negate, memberName, opName, memberType) - is Equals -> _Equals(negate, memberName, opName, op.value, memberType) - is Gt -> _Gt(negate, memberName, opName, op.value, memberType) - is Gte -> _Gte(negate, memberName, opName, op.value, memberType) - is Lt -> _Lt(negate, memberName, opName, op.value, memberType) - is Lte -> _Lte(negate, memberName, opName, op.value, memberType) - is StartsWith -> _StartsWith(negate, memberName, opName, op.value, memberType) - is IsAnyOf -> _IsAnyOf(negate, memberName, opName, op.items, memberType) + is IsNull -> _IsNull(negate, memberName, op, memberType) + is IsTrue -> _IsTrue(negate, memberName, op, memberType) + is IsFalse -> _IsFalse(negate, memberName, op, memberType) + is Equals -> _Equals(negate, memberName, op, op.value, memberType) + is Gt -> _Gt(negate, memberName, op, op.value, memberType) + is Gte -> _Gte(negate, memberName, op, op.value, memberType) + is Lt -> _Lt(negate, memberName, op, op.value, memberType) + is Lte -> _Lte(negate, memberName, op, op.value, memberType) + is StartsWith -> _StartsWith(negate, memberName, op, op.value, memberType) + is IsAnyOf -> _IsAnyOf(negate, memberName, op, op.items, memberType) is TagMapHasKey -> _TagMapHasKey(negate, memberName, op.key) is TagMapHasAnyOf -> _TagMapHasAnyOf(negate, memberName, op.tagKeys) is TagMapHasAllOf -> _TagMapHasAllOf(negate, memberName, op.tagKeys) @@ -194,32 +200,32 @@ internal class PgQueryWhereBuilder(private val request: ReadFeatures, private va } } - private fun _IsNull(negate: Boolean, memberName: String, opName: String, memberType: MemberType) { - val (at, _) = columnAndValue(memberName, opName, null, memberType) + private fun _IsNull(negate: Boolean, memberName: String, op: Op, memberType: MemberType) { + val (at, _) = columnAndValue(memberName, op, null, memberType) if (negate) where.append(at).append(" IS NOT NULL").append(' ') else where.append(at).append(" IS NULL").append(' ') } - private fun _IsTrue(negate: Boolean, memberName: String, opName: String, memberType: MemberType) { - val (at, _) = columnAndValue(memberName, opName, null, memberType) + private fun _IsTrue(negate: Boolean, memberName: String, op: Op, memberType: MemberType) { + val (at, _) = columnAndValue(memberName, op, null, memberType) if (negate) where.append(at).append('=').append(placeholderForArg(false, PgType.BOOLEAN)).append(' ') else where.append(at).append('=').append(placeholderForArg(true, PgType.BOOLEAN)).append(' ') } - private fun _IsFalse(negate: Boolean, memberName: String, opName: String, memberType: MemberType) { - val (at, _) = columnAndValue(memberName, opName, null, memberType) + private fun _IsFalse(negate: Boolean, memberName: String, op: Op, memberType: MemberType) { + val (at, _) = columnAndValue(memberName, op, null, memberType) if (negate) where.append(at).append('=').append(placeholderForArg(true, PgType.BOOLEAN)).append(' ') else where.append(at).append('=').append(placeholderForArg(false, PgType.BOOLEAN)).append(' ') } - private fun _Equals(negate: Boolean, memberName: String, opName: String, opValue: Any?, memberType: MemberType) { - val (at, value) = columnAndValue(memberName, opName, opValue, memberType) + private fun _Equals(negate: Boolean, memberName: String, op: Op, opValue: Any?, memberType: MemberType) { + val (at, value) = columnAndValue(memberName, op, opValue, memberType) if (value == null) { if (negate) where.append(at).append(" IS NOT NULL ") else where.append(at).append(" IS NULL ") } else { @@ -231,41 +237,41 @@ internal class PgQueryWhereBuilder(private val request: ReadFeatures, private va } } - private fun _Gt(negate: Boolean, memberName: String, opName: String, opValue: Any?, memberType: MemberType) { - val (at, value) = columnAndValue(memberName, opName, opValue, memberType) + private fun _Gt(negate: Boolean, memberName: String, op: Op, opValue: Any?, memberType: MemberType) { + val (at, value) = columnAndValue(memberName, op, opValue, memberType) if (negate) // NOT Greater Than where.append(at).append("<=").append(placeholderForArg(value, at)).append(' ') else // Greater Than where.append(at).append(">").append(placeholderForArg(value, at)).append(' ') } - private fun _Gte(negate: Boolean, memberName: String, opName: String, opValue: Any?, memberType: MemberType) { - val (at, value) = columnAndValue(memberName, opName, opValue, memberType) + private fun _Gte(negate: Boolean, memberName: String, op: Op, opValue: Any?, memberType: MemberType) { + val (at, value) = columnAndValue(memberName, op, opValue, memberType) if (negate) // NOT Greater Than or Equal to where.append(at).append("<").append(placeholderForArg(value, at)).append(' ') else // Greater Than or Equal to where.append(at).append(">=").append(placeholderForArg(value, at)).append(' ') } - private fun _Lt(negate: Boolean, memberName: String, opName: String, opValue: Any?, memberType: MemberType) { - val (at, value) = columnAndValue(memberName, opName, opValue, memberType) + private fun _Lt(negate: Boolean, memberName: String, op: Op, opValue: Any?, memberType: MemberType) { + val (at, value) = columnAndValue(memberName, op, opValue, memberType) if (negate) // NOT Less Than where.append(at).append(">=").append(placeholderForArg(value, at)).append(' ') else // Less Than where.append(at).append("<").append(placeholderForArg(value, at)).append(' ') } - private fun _Lte(negate: Boolean, memberName: String, opName: String, opValue: Any?, memberType: MemberType) { - val (at, value) = columnAndValue(memberName, opName, opValue, memberType) + private fun _Lte(negate: Boolean, memberName: String, op: Op, opValue: Any?, memberType: MemberType) { + val (at, value) = columnAndValue(memberName, op, opValue, memberType) if (negate) // NOT Less Than or Equal to where.append(at).append(">").append(placeholderForArg(value, at)).append(' ') else // Less Than or Equal to where.append(at).append("<=").append(placeholderForArg(value, at)).append(' ') } - private fun _StartsWith(negate: Boolean, memberName: String, opName: String, opValue: Any?, memberType: MemberType) { + private fun _StartsWith(negate: Boolean, memberName: String, op: Op, opValue: Any?, memberType: MemberType) { if (memberType != MemberType.STRING) throw illegalArg("StartsWith: The operation can only target String members") - val (at, value) = columnAndValue(memberName, opName, opValue, memberType) + val (at, value) = columnAndValue(memberName, op, opValue, memberType) if (value is Number) { // TODO: This happens for `id`. // We store identifiers as fature-number, when they are positive numbers. @@ -282,42 +288,47 @@ internal class PgQueryWhereBuilder(private val request: ReadFeatures, private va where.append("starts_with(").append(at).append(", ").append(placeholderForArg(value, at)).append(") ") } - private fun _IsAnyOf(negate: Boolean, memberName: String, opName: String, items: AnyList, memberType: MemberType) { - if (items.isEmpty()) return + private fun _IsAnyId(negate: Boolean, items: AnyList) { + // First detect which identifiers need to be search in `id` and which in `fn` + val fn_array = LongArray(items.size) + var fn_end = 0 + val id_array = arrayOfNulls(items.size) + var id_end = 0 + for (item in items) { + // We simply ignore invalid types. + if (item !is String) continue + val numeric = featureNumberAsLong(item) + if (numeric >= 0L) { + fn_array[fn_end++] = numeric + } else { + id_array[id_end++] = item + } + } + if (fn_end == 0 && id_end == 0) return // Only invalid values. + val hasBoth = fn_end > 0 && id_end > 0 + if (negate) where.append("NOT ") + if (hasBoth) where.append('(') + if (fn_end > 0) { + val placeholder = if (fn_array.size == fn_end) placeholderForArg(fn_array, PgType.INT64_ARRAY) + else placeholderForArg(fn_array.copyOf(fn_end), PgType.INT64_ARRAY) + where.append(FeatureNumber.name).append("=ANY(").append(placeholder).append(")") + } + if (hasBoth) where.append(" OR ") + if (id_end > 0) { + val placeholder = if (id_array.size == id_end) placeholderForArg(id_array, PgType.STRING_ARRAY) + else placeholderForArg(id_array.copyOf(id_end), PgType.STRING_ARRAY) + where.append(Id.name).append("=ANY(").append(placeholder).append(")") + } + if (hasBoth) where.append(") ") else where.append(' ') + } + private fun _IsAnyOf(negate: Boolean, memberName: String, op: Op, items: AnyList, memberType: MemberType) { + if (items.isEmpty()) return // For `id` we can have a mixture of strings and numbers. - // We simply ignore invalid values being in the array. if (memberName == Id.name) { - val fn_array = LongArray(items.size) - var fn_end = 0 - val id_array = arrayOfNulls(items.size) - var id_end = 0 - for (item in items) { - if (item !is String) continue - val numeric = featureNumberAsLong(item) - if (numeric >= 0L) { - fn_array[fn_end++] = numeric - } else { - id_array[id_end++] = item - } - } - if (negate) where.append("NOT ") - where.append('(') - if (fn_end > 0) { - val placeholder = if (fn_array.size == fn_end) placeholderForArg(fn_array, PgType.INT64_ARRAY) - else placeholderForArg(fn_array.copyOf(fn_end), PgType.INT64_ARRAY) - where.append(FeatureNumber.name).append("= ANY(").append(placeholder).append(")") - } - if (id_end > 0) { - if (fn_end > 0) where.append(" OR ") - val placeholder = if (id_array.size == id_end) placeholderForArg(id_array, PgType.STRING_ARRAY) - else placeholderForArg(id_array.copyOf(id_end), PgType.STRING_ARRAY) - where.append(Id.name).append("= ANY(").append(placeholder).append(")") - } - where.append(") ") + _IsAnyId(negate, items) return } - // For all other members the values are uniform and only one column is queried. val at = memberColumn(memberName) val (values, arrayType) = when(memberType) { @@ -329,7 +340,7 @@ internal class PgQueryWhereBuilder(private val request: ReadFeatures, private va MemberType.FLOAT64 -> Pair(items.toDoubleArray(true), PgType.DOUBLE_ARRAY) MemberType.STRING -> Pair(items.toStringArray(true), PgType.STRING_ARRAY) MemberType.BYTE_ARRAY -> Pair(items.toByteArrayArray(true), PgType.BYTE_ARRAY_ARRAY) - else -> throw illegalArg("The member '$memberName' can't be used for $opName") + else -> throw illegalArg("The member '$memberName' can't be used for ${op.op}") } val placeholder = placeholderForArg(values, arrayType) if (negate) where.append("NOT ") @@ -488,7 +499,7 @@ internal class PgQueryWhereBuilder(private val request: ReadFeatures, private va val geometryToCompare = if (transformers.isEmpty()) basicGeometry else resolveTransformation(transformers, basicGeometry) if (negate) where.append("NOT ") - where.append("ST_Intersects(naksha_2d($memberName), $geometryToCompare)") + where.append("ST_Intersects(naksha_2d($memberName), $geometryToCompare) ") } /** @@ -659,63 +670,6 @@ internal class PgQueryWhereBuilder(private val request: ReadFeatures, private va } } - private fun whereFeatureId() { - // Partition into numeric IDs (fn >= 0, id stored as NULL in DB) and named IDs (fn < 0, id NOT NULL). - val reqIds: StringList = request.featureIds - val featureNumbers: MutableList = mutableListOf() - val featureIds: MutableList = mutableListOf() - for (id in reqIds) { - if (id == null) continue - val fn = Naksha.featureNumber(id) - if (fn >= 0L) { - featureNumbers.add(fn) - } else { - featureIds.add(id) - } - } - if (featureNumbers.isEmpty() && featureIds.isEmpty()) return - - // For each collection: - if (where.isNotEmpty()) where.append(" AND ") - - where.append("( ") - if (featureIds.isNotEmpty()) { - val op = IsAnyOf(at = StandardMembers.Id, items = featureIds.toTypedArray()) - applyOp(op) - } - if (featureNumbers.isNotEmpty()) { - if (featureIds.isNotEmpty()) where.append(" OR ") - - val op = IsAnyOf(at = StandardMembers.FeatureNumber, items = featureNumbers.toTypedArray()) - applyOp(op) - } - where.append(")") - } - - // TODO: Do we need this, and if so, how do we integrate into changed code? -// private fun whereRefTiles() { -// val hereTiles = request.query.refTiles -// .filterNotNull() -// .map { HereTile(it) } -// if (hereTiles.isNotEmpty()) { -// if (where.isNotEmpty()) { -// where.append(" AND (") -// } else { -// where.append(" (") -// } -// where.append(refPointInAnyOfTiles(hereTiles)) -// where.append(")") -// } -// } -// -// private fun refPointInAnyOfTiles(hereTiles: List): String { -// return hereTiles.joinToString(separator = " OR ") { hereTile -> -// refPointInTile(hereTile) -// } -// } - - // --------------------------------------------------------< OLD CODE >------------------------------------------------------------- -// private fun whereGuids() { val tupleNumbers = request.guids.mapNotNull { it?.tupleNumber } if (tupleNumbers.isNotEmpty()) { @@ -732,380 +686,4 @@ internal class PgQueryWhereBuilder(private val request: ReadFeatures, private va where.append("($FnColumn, $VersionColumn) IN (SELECT * FROM unnest($featureNumbersArg::int8[], $versionsArg::int8[]))") } } -// -// private fun whereVersion() { -// val version = request.version -// if (version != null) { -// if (where.isNotEmpty()) where.append(" AND ") -// where.append("$VERSION <= ${version.toInt()}") -// } -// val minVersion = request.minVersion -// if (minVersion != null) { -// if (where.isNotEmpty()) where.append(" AND ") -// where.append("$VERSION >= ${minVersion.toInt()}") -// } -// } -// -// private fun whereSpatial() { -// val spatialQuery = request.query.spatial -// if (spatialQuery != null) { -// if (where.isNotEmpty()) { -// where.append(" AND (") -// } else { -// where.append(" (") -// } -// whereNestedSpatial(spatialQuery) -// where.append(")") -// } -// } -// -// private fun whereNestedSpatial(spatial: ISpatialQuery) { -// when (spatial) { -// is SpNot -> not( -// subClause = spatial.query, -// subClauseResolver = this::whereNestedSpatial -// ) -// -// is SpAnd -> and( -// subClauses = spatial.filterNotNull(), -// subClauseResolver = this::whereNestedSpatial -// ) -// -// is SpOr -> or( -// subClauses = spatial.filterNotNull(), -// subClauseResolver = this::whereNestedSpatial -// ) -// -// is SpIntersects -> { -// val queryGeometry = nakshaGeometry(spatial.geometry) -// val geometryToCompare = when (val transformation = spatial.transformation) { -// null -> queryGeometry -// else -> resolveTransformation(transformation, queryGeometry) -// } -// where.append("ST_Intersects(naksha_2d(${StandardMembers.Geometry}), $geometryToCompare)") -// } -// -// is SpRefInHereTile -> { -// where.append(refPointInTile(spatial.getHereTile())) -// } -// -// else -> throw NakshaException( -// NakshaError.ILLEGAL_ARGUMENT, -// "Invalid spatial query found: $spatial" -// ) -// } -// } -// -// -// private fun whereRefTiles() { -// val hereTiles = request.query.refTiles -// .filterNotNull() -// .map { HereTile(it) } -// if (hereTiles.isNotEmpty()) { -// if (where.isNotEmpty()) { -// where.append(" AND (") -// } else { -// where.append(" (") -// } -// where.append(refPointInAnyOfTiles(hereTiles)) -// where.append(")") -// } -// } -// -// private fun refPointInAnyOfTiles(hereTiles: List): String { -// return hereTiles.joinToString(separator = " OR ") { hereTile -> -// refPointInTile(hereTile) -// } -// } -// -// private fun refPointInTile(hereTile: HereTile): String { -// val lowerBoundPlaceholder = placeholderForArg( -// hereTile.maxLevelLowerBound().intKey, -// PgType.INT -// ) -// val upperBoundPlaceholder = placeholderForArg( -// hereTile.maxLevelUpperBound().intKey, -// PgType.INT -// ) -// return "(${StandardMembers.HereTile} >= $lowerBoundPlaceholder AND ${StandardMembers.HereTile} <= $upperBoundPlaceholder)" -// } -// -// private fun whereMetadata() { -// val metaQuery = request.query.members -// if (metaQuery != null) { -// if (where.isNotEmpty()) { -// where.append(" AND (") -// } else { -// where.append(" (") -// } -// whereNestedMetadata(metaQuery) -// where.append(")") -// } -// } -// -// private fun whereNestedMetadata(metaQuery: IMemberQuery) { -// when (metaQuery) { -// is MemberNot -> not( -// subClause = metaQuery.query, -// subClauseResolver = this::whereNestedMetadata -// ) -// -// is MemberAnd -> and( -// subClauses = metaQuery.filterNotNull(), -// subClauseResolver = this::whereNestedMetadata -// ) -// -// is MemberOr -> or( -// subClauses = metaQuery.filterNotNull(), -// subClauseResolver = this::whereNestedMetadata -// ) -// -// is MemberQuery -> { -// val isActionQuery = metaQuery.member == MetaColumn.action() -// val pgColumn = -// if (isActionQuery) { -// StandardMembers.Version -// } else { -// PgColumn.ofRowColumn(metaQuery.member) ?: throw NakshaException( -// NakshaError.ILLEGAL_STATE, -// "Couldn't find PgColumn for TupleColumn: ${metaQuery.member.name}" -// ) -// } -// val leftOperand = if (isActionQuery) { -// "(${PgColumn.version.name} & 3)::int4" -// } else if (pgColumn == PgColumn.created_at || pgColumn == PgColumn.author_ts) { -// "COALESCE(${pgColumn.name}, ${PgColumn.updated_at.name})" -// } else { -// pgColumn.name -// } -// // Action lives in the lower 2 bits of `version`; the comparison value is a small int. -// val placeholderType = if (isActionQuery) PgType.INT else pgColumn.type -// val resolvedQuery = when (val op = metaQuery.op) { -// is StringOp -> { -// val placeholder = placeholderForArg(metaQuery.value, placeholderType) -// resolveStringOp(op, leftOperand, placeholder) -// } -// is DoubleOp -> { -// val placeholder = placeholderForArg(metaQuery.value, placeholderType) -// resolveDoubleOp(op, leftOperand, placeholder) -// } -// is AnyOp.IS_ANY_OF -> { -// val placeholder = placeholderForArg(metaQuery.value, arrayTypeFor(placeholderType)) -// "$leftOperand = ANY($placeholder)" -// } -// else -> throw illegalArg("Unknown op type: ${op::class.simpleName}") -// } -// where.append(resolvedQuery) -// } -// -// else -> throw NakshaException( -// NakshaError.ILLEGAL_ARGUMENT, -// "Unknown metadata query type: ${metaQuery::class.simpleName}" -// ) -// } -// } -// -// private fun arrayTypeFor(pgType: PgType): PgType { -// return when (pgType) { -// PgType.BOOLEAN -> PgType.BOOLEAN_ARRAY -// PgType.SHORT -> PgType.SHORT_ARRAY -// PgType.INT -> PgType.INT_ARRAY -// PgType.INT64 -> PgType.INT64_ARRAY -// PgType.FLOAT -> PgType.FLOAT_ARRAY -// PgType.DOUBLE -> PgType.DOUBLE_ARRAY -// PgType.STRING -> PgType.STRING_ARRAY -// PgType.BYTE_ARRAY -> PgType.BYTE_ARRAY_ARRAY -// else -> throw illegalArg("Unknown array type for PgType: ${pgType::class.simpleName}") -// } -// } -// -// private fun whereTags() { -// val tagQuery = request.query.tags -// if (tagQuery != null) { -// if (where.isNotEmpty()) { -// where.append(" AND (") -// } else { -// where.append(" (") -// } -// whereNestedTags(tagQuery) -// where.append(")") -// } -// } -// -// private fun whereNestedTags(tagQuery: ITagQuery) { -// when (tagQuery) { -// is TagSetContains -> resolveTagSetContains(tagQuery) -// is TagNot -> not(tagQuery.query, this::whereNestedTags) -// is TagOr -> { -// if(containsOnlyTagExists(tagQuery)){ -// // for tags without values we can utilize top-level-key based '?|' operand -// // https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE -// val tagNames = tagQuery.filterIsInstance().map { it.name } -// resolveTagNamesArrayOperation( -// jsonbOperator = "?|", // 'jsonb_exists_any' is equivalent but will not hit the GIN index -// tagNames = tagNames -// ) -// } else { -// or(tagQuery.filterNotNull(), this::whereNestedTags) -// } -// } -// is TagAnd -> { -// if(containsOnlyTagExists(tagQuery)){ -// // for tags without values we can utilize top-level-key based '?&' operand -// // https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE -// val tagNames = tagQuery.filterIsInstance().map { it.name } -// resolveTagNamesArrayOperation( -// jsonbOperator = "?&", // 'jsonb_exists_all' is equivalent but MIGHT not hit the GIN index -// tagNames = tagNames -// ) -// } else { -// and(tagQuery.filterNotNull(), this::whereNestedTags) -// } -// } -// is TagQuery -> resolveSingleTagQuery(tagQuery) -// } -// } -// -// private fun containsOnlyTagExists(container: ListProxy): Boolean = -// container.all { it == null || it is TagMapHasKey } -// -// /** -// * Element containment on a set-form tags column (jsonb array): `tags @> '[]'::jsonb`. -// * The `@>` operator matches the element in its type (string, boolean, number) and is supported -// * by the GIN index over the column. -// */ -// private fun resolveTagSetContains(tagQuery: TagSetContains) { -// val element = AnyList() -// element.add(tagQuery.element) -// val placeholder = placeholderForArg(toJSON(element), PgType.STRING) -// where.append("$tagsAsJsonb @> $placeholder::jsonb") -// } -// -// private fun resolveTagNamesArrayOperation(jsonbOperator: String, tagNames: List) { -// val tagKeysArray = tagNames.toTypedArray() -// val tagKeysPlaceholder = placeholderForArg(tagKeysArray, PgType.STRING_ARRAY) -// where.append("$tagsAsJsonb ?$jsonbOperator $tagKeysPlaceholder") -// } -// -// private fun resolveSingleTagQuery(tagQuery: TagQuery) { -// when (tagQuery) { -// is TagMapHasKey -> { -// val tagNamePlaceholder = placeholderForArg(tagQuery.name, PgType.STRING) -// where.append("$tagsAsJsonb ?? $tagNamePlaceholder") -// } -// -// is TagValueIsNull -> { -// val tagValuePlaceholder = placeholderForArg(selectTagValue(tagQuery), PgType.STRING) -// where.append("$tagValuePlaceholder IS NULL") -// } -// -// is TagValueIsBool -> { -// if (tagQuery.value) { -// where.append(selectTagValue(tagQuery, PgType.BOOLEAN)) -// } else { -// where.append("not(${selectTagValue(tagQuery, PgType.BOOLEAN)})") -// } -// } -// -// is TagValueIsDouble -> { -// val queryValuePlaceholder = placeholderForArg(tagQuery.value, PgType.DOUBLE) -// val doubleOp = resolveDoubleOp( -// tagQuery.op, -// selectTagValue(tagQuery, PgType.DOUBLE), -// queryValuePlaceholder -// ) -// where.append(doubleOp) -// } -// -// is TagValueIsString -> { -// val queryValuePlaceholder = placeholderForArg(tagQuery.value, PgType.STRING) -// val stringEquals = resolveStringOp( -// StringOp.EQUALS, -// selectTagValue(tagQuery, PgType.STRING), -// queryValuePlaceholder -// ) -// where.append(stringEquals) -// } -// -// is TagValueMatches -> { -// val jsonPathPlaceholder = placeholderForArg( -// "\$.${tagQuery.name} ? (@ like_regex \"${tagQuery.regex}\")", -// PgType.STRING -// ) -// where.append("$tagsAsJsonb @?? $jsonPathPlaceholder::jsonpath") -// } -// } -// } -// -// private fun selectTagValue(tagQuery: TagQuery, castTo: PgType? = null): String { -// val tagKeyPlaceholder = placeholderForArg(tagQuery.name, PgType.STRING) -// return when (castTo) { -// null -> "$tagsAsJsonb->$tagKeyPlaceholder" -// PgType.STRING -> "$tagsAsJsonb->>$tagKeyPlaceholder" -// else -> "($tagsAsJsonb->$tagKeyPlaceholder)::${castTo.value}" -// } -// } -// -// private fun not(subClause: T, subClauseResolver: (T) -> Unit) { -// where.append(" NOT (") -// subClauseResolver(subClause) -// where.append(") ") -// } -// -// private fun and(subClauses: List, subClauseResolver: (T) -> Unit) = -// multiClause("AND", subClauses, subClauseResolver) -// -// private fun or(subClauses: List, subClauseResolver: (T) -> Unit) = -// multiClause("OR", subClauses, subClauseResolver) -// -// private fun multiClause( -// operand: String, -// subClauses: List, -// subClauseResolver: (T) -> Unit -// ) { -// where.append(" (") -// subClauses.forEachIndexed { index, subClause -> -// if (index > 0) { -// where.append(" $operand ") -// } -// subClauseResolver(subClause) -// } -// where.append(") ") -// } -// -// -// private fun resolveStringOp( -// stringOp: StringOp, -// leftOperand: String, -// rightOperand: String -// ): String { -// return when (stringOp) { -// StringOp.EQUALS -> "$leftOperand = $rightOperand" -// StringOp.NOT_EQUALS -> "$leftOperand != $rightOperand" -// StringOp.STARTS_WITH -> "starts_with($leftOperand, $rightOperand)" -// else -> throw NakshaException( -// NakshaError.ILLEGAL_ARGUMENT, -// "Unknown StringOp: $stringOp" -// ) -// } -// } -// -// private fun resolveDoubleOp( -// doubleOp: DoubleOp, -// leftOperand: String, -// rightOperand: String -// ): String { -// return when (doubleOp) { -// DoubleOp.EQ -> "$leftOperand = $rightOperand" -// DoubleOp.NE -> "$leftOperand != $rightOperand" -// DoubleOp.GT -> "$leftOperand > $rightOperand" -// DoubleOp.GTE -> "$leftOperand >= $rightOperand" -// DoubleOp.LT -> "$leftOperand < $rightOperand" -// DoubleOp.LTE -> "$leftOperand <= $rightOperand" -// else -> throw NakshaException( -// NakshaError.ILLEGAL_ARGUMENT, -// "Unknown DoubleOp: $doubleOp" -// ) -// } -// } } From 0bcf0f733d0447dbf66db75a949801e463c9c9cf Mon Sep 17 00:00:00 2001 From: Alexander Lowey-Weber Date: Mon, 31 Aug 2026 17:04:34 +0200 Subject: [PATCH 27/41] Fix activity log, do not mix old and new query style. Fix TagList test, default is normalized. Signed-off-by: Alexander Lowey-Weber --- .../ActivityLogRequestTranslationUtil.java | 26 +++++++---- ...ActivityLogRequestTranslationUtilTest.java | 45 ++++++++++--------- .../commonMain/kotlin/naksha/model/XyzNs.kt | 4 +- .../kotlin/naksha/model/XyzProxyTest.kt | 6 +-- 4 files changed, 49 insertions(+), 32 deletions(-) diff --git a/here-naksha-handler-activitylog/src/jvmMain/java/com/here/naksha/handler/activitylog/ActivityLogRequestTranslationUtil.java b/here-naksha-handler-activitylog/src/jvmMain/java/com/here/naksha/handler/activitylog/ActivityLogRequestTranslationUtil.java index 86a51557b..d7c9b834b 100644 --- a/here-naksha-handler-activitylog/src/jvmMain/java/com/here/naksha/handler/activitylog/ActivityLogRequestTranslationUtil.java +++ b/here-naksha-handler-activitylog/src/jvmMain/java/com/here/naksha/handler/activitylog/ActivityLogRequestTranslationUtil.java @@ -29,11 +29,9 @@ import naksha.base.Guid; import naksha.base.TupleNumber; import naksha.model.objects.StandardMembers; +import naksha.model.objects.XyzMembers; import naksha.model.request.ReadFeatures; -import naksha.model.request.ops.And; -import naksha.model.request.ops.Equals; -import naksha.model.request.ops.OpList; -import naksha.model.request.ops.Or; +import naksha.model.request.ops.*; import naksha.model.request.query.PQuery; import naksha.model.request.query.Property; import naksha.model.request.query.StringOp; @@ -92,18 +90,30 @@ static void transformOriginalRequest(ReadFeatures readFeatures, String spaceId) } readFeatures.setQueryMembers(or); } - StringList finalFeatureIds = new StringList(); - // extractFeatureIds from activityLogId - populate featureIds Set disabledActivityLogPOps = disablePQueriesInRequest( readFeatures.getQuery(), ActivityLogRequestTranslationUtil::isSingleActivityLogIdEqualityQuery ); + + final StringList featureIds = new StringList(); if (!disabledActivityLogPOps.isEmpty()) { - disabledActivityLogPOps.forEach(activityLogOp -> finalFeatureIds.add(String.valueOf(activityLogOp.getValue()))); + disabledActivityLogPOps.forEach(activityLogOp -> featureIds.add(String.valueOf(activityLogOp.getValue()))); readFeatures.refreshPropertyFilter(); } - readFeatures.setFeatureIds(finalFeatureIds); + // Translated from old syntax into new members query, because we do not allow to mix old and new syntax! + // TODO: Why do we need this? + if (!featureIds.isEmpty()) { + final IsAnyOf searchFeaturesByIdOp = new IsAnyOf(XyzMembers.XyzId); + for (var id : featureIds) searchFeaturesByIdOp.getItems().add(id); + + final Op existing = readFeatures.getQueryMembers(); + if (existing == null) + readFeatures.setQueryMembers(searchFeaturesByIdOp); + else + readFeatures.setQueryMembers(new And(existing, searchFeaturesByIdOp)); + } + readFeatures.setFeatureIds(new StringList()); } private static boolean isSingleActivityLogIdEqualityQuery(PQuery pQuery) { diff --git a/here-naksha-handler-activitylog/src/jvmTest/java/com/here/naksha/handler/activitylog/ActivityLogRequestTranslationUtilTest.java b/here-naksha-handler-activitylog/src/jvmTest/java/com/here/naksha/handler/activitylog/ActivityLogRequestTranslationUtilTest.java index c4832132c..9d66f3a4c 100644 --- a/here-naksha-handler-activitylog/src/jvmTest/java/com/here/naksha/handler/activitylog/ActivityLogRequestTranslationUtilTest.java +++ b/here-naksha-handler-activitylog/src/jvmTest/java/com/here/naksha/handler/activitylog/ActivityLogRequestTranslationUtilTest.java @@ -5,6 +5,7 @@ import static com.here.naksha.handler.activitylog.GuidUtil.guid; import static com.here.naksha.handler.activitylog.GuidUtil.randomVersion; import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.util.ArrayList; import java.util.List; @@ -47,6 +48,26 @@ void shouldTranslateSingleGuidPassedAsFeatureId() { checkOpIsUuidRequest(op, List.of(guid.tupleNumber.version)); } + private void checkOpIsIdRequest(Op op, List ids) { + final IsAnyOf featureIdsOp = assertInstanceOf(IsAnyOf.class, op); + assertNotNull(featureIdsOp); + var items = featureIdsOp.getItems(); + assertEquals(ids.size(), items.size()); + for (var id : ids) assertTrue(items.contains(id)); + } + + private void checkOpIsUuidAndIdRequest(final Op op, final List versions, final List ids) { + // We assume that op is Or(versions, ids) + final And andOp = assertInstanceOf(And.class, op); + assertEquals(2, andOp.getChildren().size()); + + // First uuid's + checkOpIsUuidRequest(andOp.getChildren().getFirst(), versions); + + // second ids + checkOpIsIdRequest(andOp.getChildren().get(1), ids); + } + private void checkOpIsUuidRequest(final Op op, final List versions) { assertInstanceOf(Or.class, op); OpList orChildren = ((Or) op).getChildren(); @@ -124,15 +145,10 @@ void shouldTranslateActivityLogIdToFeatureId() { assertNull(readFeatures.getVersion()); // And: there is a single featureId withing the request - StringList featureIds = readFeatures.getFeatureIds(); - assertEquals(1, featureIds.getSize()); - assertEquals(featureId, featureIds.get(0)); + checkOpIsIdRequest(readFeatures.getQueryMembers(), List.of(featureId)); // And: assertNull(readFeatures.getQuery().getProperties()); - - // And: there are no guids (nothing was declared in original featureIds) - assertNull(readFeatures.getQueryMembers()); } @Test @@ -154,15 +170,10 @@ void shouldTranslateActivityLogIdsToFeatureIds() { verifyAllHistoricalVersionsInCollection(readFeatures); // And: all ids defined in AcitvityLogNs are now part of featureIds - StringList featureIds = readFeatures.getFeatureIds(); - assertEquals(2, featureIds.getSize()); - assertTrue(featureIds.containsAll(List.of(firstId, secondId))); + checkOpIsIdRequest(readFeatures.getQueryMembers(), List.of(firstId, secondId)); // And: the pQuery left is effectively dead assertNull(readFeatures.getQuery().getProperties()); - - // And: there are no guids (nothing was declared in original featureIds) - assertNull(readFeatures.getQueryMembers()); } @Test @@ -185,14 +196,8 @@ void shouldApplyMixedTranslations() { // Then: request will reach correct collection and history verifyAllHistoricalVersionsInCollection(readFeatures); - // And: feature ids are populated from ActivityLogNs - StringList finalFeatureIds = readFeatures.getFeatureIds(); - assertEquals(1, finalFeatureIds.getSize()); - assertEquals(activityLogId, finalFeatureIds.get(0)); - - // And: guuids are populated from original feature ids - Op op = readFeatures.getQueryMembers(); - checkOpIsUuidRequest(op, List.of(version)); + // And: uuid's and ids are populated from original request + checkOpIsUuidAndIdRequest(readFeatures.getQueryMembers(), List.of(version), List.of(activityLogId)); } private void verifyAllHistoricalVersionsInCollection(ReadFeatures readFeatures) { diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/XyzNs.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/XyzNs.kt index 154941d2f..dabe45456 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/XyzNs.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/XyzNs.kt @@ -24,6 +24,7 @@ import naksha.model.objects.XyzMembers.XyzMembers_C.XyzUpdatedAt import kotlin.DeprecationLevel.WARNING import kotlin.js.JsExport import kotlin.js.JsStatic +import kotlin.jvm.JvmOverloads import kotlin.jvm.JvmStatic /** @@ -729,7 +730,8 @@ class XyzNs : AnyObject() { * @param tags The tags to set. * @param normalize `true` if the given tags should be normalized; `false`, if they are already normalized. */ - fun setTags(tags: TagList?, normalize: Boolean): XyzNs { + @JvmOverloads + fun setTags(tags: TagList?, normalize: Boolean = true): XyzNs { if (normalize) { if (tags != null ) { for ((i, tag) in tags.withIndex()) { diff --git a/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/XyzProxyTest.kt b/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/XyzProxyTest.kt index 85013e3ad..13aafec3f 100644 --- a/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/XyzProxyTest.kt +++ b/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/XyzProxyTest.kt @@ -154,13 +154,13 @@ class XyzProxyTest { val xyz = XyzNs() // when - xyz.setTags(TagList("Alicja", "Baba", "Alan"), false) + xyz.setTags(TagList("Alicja", "Baba", "Alan", skipNormalize = true), normalize = false) // then - assertEquals(listOf("Alicja", "Baba", "Alan"), xyz.tags?.toList()) + assertEquals(listOf("Alicja", "Baba", "Alan"), xyz.tags.toList()) // when xyz.setTags(TagList("Cecil"), true) - assertEquals(listOf("cecil"), xyz.tags?.toList()) + assertEquals(listOf("cecil"), xyz.tags.toList()) } } \ No newline at end of file From 615fb8f02fdf039fc3e9a4e6ddfbfaf0e748d081 Mon Sep 17 00:00:00 2001 From: Alexander Lowey-Weber Date: Tue, 1 Sep 2026 10:35:29 +0200 Subject: [PATCH 28/41] Fix minor issue left from rebase and Int64 to Long switch. Signed-off-by: Alexander Lowey-Weber --- .../java/com/here/naksha/app/service/PatchFeatureTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/here-naksha-app-service/src/jvmTest/java/com/here/naksha/app/service/PatchFeatureTest.java b/here-naksha-app-service/src/jvmTest/java/com/here/naksha/app/service/PatchFeatureTest.java index 3fbc5ebc1..7e651244e 100644 --- a/here-naksha-app-service/src/jvmTest/java/com/here/naksha/app/service/PatchFeatureTest.java +++ b/here-naksha-app-service/src/jvmTest/java/com/here/naksha/app/service/PatchFeatureTest.java @@ -114,7 +114,7 @@ void testPatchOneFeatureByIdWrongUuid() throws Exception { tupleNumber.catalogNumber, tupleNumber.collectionNumber, tupleNumber.featureNumber, - tupleNumber.version.minus(4) //older, invalid version, to simulate wrong uuid + tupleNumber.version - 4L //older, invalid version, to simulate wrong uuid )).toString(); // NOTE: if the wrong uuid is different in databaseNumber, or catalogNumber, or collectionNumber, the response will be 400 (mapped from NakshaError.ILLEGAL_ARGUMENT, thrown by storage) instead of 409. // But this requires manual modification of the uuid in the input JSON, which is not an expected behavior from the client, so we don't handle that currently. From 09cfe1a8a1526c471c97cbdf027c43e47e3936b4 Mon Sep 17 00:00:00 2001 From: Alexander Lowey-Weber Date: Wed, 2 Sep 2026 09:56:17 +0200 Subject: [PATCH 29/41] Added check that readFeatures.getFeatureIds() is empty Signed-off-by: Alexander Lowey-Weber --- .../activitylog/ActivityLogRequestTranslationUtilTest.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/here-naksha-handler-activitylog/src/jvmTest/java/com/here/naksha/handler/activitylog/ActivityLogRequestTranslationUtilTest.java b/here-naksha-handler-activitylog/src/jvmTest/java/com/here/naksha/handler/activitylog/ActivityLogRequestTranslationUtilTest.java index 9d66f3a4c..96d20247a 100644 --- a/here-naksha-handler-activitylog/src/jvmTest/java/com/here/naksha/handler/activitylog/ActivityLogRequestTranslationUtilTest.java +++ b/here-naksha-handler-activitylog/src/jvmTest/java/com/here/naksha/handler/activitylog/ActivityLogRequestTranslationUtilTest.java @@ -22,6 +22,7 @@ import naksha.model.request.query.StringOp; import org.junit.jupiter.api.Test; +@SuppressWarnings("deprecation") class ActivityLogRequestTranslationUtilTest { private static final String TEST_SPACE_ID = "test_space_id"; @@ -149,6 +150,7 @@ void shouldTranslateActivityLogIdToFeatureId() { // And: assertNull(readFeatures.getQuery().getProperties()); + assertTrue(readFeatures.getFeatureIds().isEmpty()); } @Test @@ -174,6 +176,7 @@ void shouldTranslateActivityLogIdsToFeatureIds() { // And: the pQuery left is effectively dead assertNull(readFeatures.getQuery().getProperties()); + assertTrue(readFeatures.getFeatureIds().isEmpty()); } @Test From 64d88d56075eb2b260e26fd38056c83b2c37ea72 Mon Sep 17 00:00:00 2001 From: Alexander Lowey-Weber Date: Thu, 3 Sep 2026 16:10:09 +0200 Subject: [PATCH 30/41] Fix addTag call in constructor to use skipNormalize. Signed-off-by: Alexander Lowey-Weber --- .../src/commonMain/kotlin/naksha/model/TagList.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TagList.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TagList.kt index 84649d13a..7acb2be24 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TagList.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TagList.kt @@ -43,7 +43,7 @@ class TagList() : StringList(), ITagList { setCapacity(tags.size) for (i in 0 until tags.size) { val tag = tags[i] - if (tag is String) addTag(tag, skipInvalid) + if (tag is String) addTag(tag, !skipNormalize) else if (tag is Char || tag is CharSequence) addTag(tag.toString(), !skipNormalize) else if (!skipInvalid) throw illegalArg("The tag $i is no string: $tag") } From 423acf932d346a03b106218289db161fe2e170af Mon Sep 17 00:00:00 2001 From: Alexander Lowey-Weber Date: Thu, 3 Sep 2026 16:10:48 +0200 Subject: [PATCH 31/41] Modify coerceSpatial in Tuple to make the execution path clearer. Signed-off-by: Alexander Lowey-Weber --- .../src/commonMain/kotlin/naksha/model/Tuple.kt | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/Tuple.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/Tuple.kt index 2c0c46e4d..2684f6283 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/Tuple.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/Tuple.kt @@ -494,8 +494,9 @@ data class Tuple @JvmOverloads constructor( is ByteArray -> fromTWKB(value) else -> value.proxy(SpGeometry::class) } - return geometry - ?: { warnMismatch(featureId, memberName, "SpGeometry", value); null } as SpGeometry? + if (geometry != null) return geometry + warnMismatch(featureId, memberName, "SpGeometry", value); + return null } private fun coerceTagMap(value: Any, featureId: String, memberName: String): TagMap? { @@ -503,9 +504,6 @@ data class Tuple @JvmOverloads constructor( if (tagMap != null) return tagMap warnMismatch(featureId, memberName, "TagMap", value) return null - // TODO: Nice Compiler Bug, this code should replace the above, but compiler complains! - // The exact same code works above in `coerceSpatial` ? - // return tagMap ?: { warnMismatch(featureId, memberName, "TagMap", value); null } as TagMap? } private fun coerceTagList(value: Any, featureId: String, memberName: String): TagList? { From 84ddbecd53d8e926d1094361f87a24313ccdda17 Mon Sep 17 00:00:00 2001 From: Alexander Lowey-Weber Date: Thu, 3 Sep 2026 16:11:12 +0200 Subject: [PATCH 32/41] Fix that when an operation is a no-op, AND and OR to not linger. Signed-off-by: Alexander Lowey-Weber --- .../src/commonMain/kotlin/naksha/psql/PgQueryWhereBuilder.kt | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgQueryWhereBuilder.kt b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgQueryWhereBuilder.kt index 88cccdfc0..52ee0c210 100644 --- a/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgQueryWhereBuilder.kt +++ b/here-naksha-lib-psql/src/commonMain/kotlin/naksha/psql/PgQueryWhereBuilder.kt @@ -139,6 +139,8 @@ internal class PgQueryWhereBuilder(private val request: ReadFeatures, private va if (child == null) continue if (first) first = false else where.append("AND ") applyOp(child) + // If the applyOp does not add anything, so is a no-op, remove the AND. + if (where.endsWith("AND ")) where.setLength(where.length - "AND ".length) } if (children.size > 1) where.append(") ") else where.append(" ") return @@ -153,6 +155,8 @@ internal class PgQueryWhereBuilder(private val request: ReadFeatures, private va if (child == null) continue if (first) first = false else where.append("OR ") applyOp(child) + // If the applyOp does not add anything, so is a no-op, remove the OR. + if (where.endsWith("OR ")) where.setLength(where.length - "OR ".length) } if (children.size > 1) where.append(") ") else where.append(" ") return From ad03b52f3a09f85c0bcdba7f949e9fde9d4b0fb5 Mon Sep 17 00:00:00 2001 From: Alexander Lowey-Weber Date: Fri, 4 Sep 2026 12:46:19 +0200 Subject: [PATCH 33/41] Fix tests that faulty expect not normalized tag. Signed-off-by: Alexander Lowey-Weber --- .../TC5030_patchFeature/feature_response_part.json | 2 +- .../TC5031_patchFeature/feature_response_part.json | 2 +- .../TC5032_patchFeature/feature_response_part.json | 2 +- .../TC01_patchFeatureOnlyInBase/response_body_part.json | 2 +- .../TC02_patchFeatureOnlyInDelta/response_body_part.json | 2 +- .../TC2000_createFeatureWithoutTag/feature_response_part.json | 2 +- .../TC2001_createFeatureWithTag/feature_response_part.json | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/here-naksha-app-service/src/jvmTest/resources/unit_test_data/DefaultViewHandler/TC5030_patchFeature/feature_response_part.json b/here-naksha-app-service/src/jvmTest/resources/unit_test_data/DefaultViewHandler/TC5030_patchFeature/feature_response_part.json index 96e980819..a79c06c11 100644 --- a/here-naksha-app-service/src/jvmTest/resources/unit_test_data/DefaultViewHandler/TC5030_patchFeature/feature_response_part.json +++ b/here-naksha-app-service/src/jvmTest/resources/unit_test_data/DefaultViewHandler/TC5030_patchFeature/feature_response_part.json @@ -24,7 +24,7 @@ }, "@ns:com:here:xyz": { "tags": [ - "xyz_source_id_COM_1000001_20240214" + "xyz_source_id_com_1000001_20240214" ] }, "speedLimit": "50", diff --git a/here-naksha-app-service/src/jvmTest/resources/unit_test_data/DefaultViewHandler/TC5031_patchFeature/feature_response_part.json b/here-naksha-app-service/src/jvmTest/resources/unit_test_data/DefaultViewHandler/TC5031_patchFeature/feature_response_part.json index 973545ffb..41def6499 100644 --- a/here-naksha-app-service/src/jvmTest/resources/unit_test_data/DefaultViewHandler/TC5031_patchFeature/feature_response_part.json +++ b/here-naksha-app-service/src/jvmTest/resources/unit_test_data/DefaultViewHandler/TC5031_patchFeature/feature_response_part.json @@ -24,7 +24,7 @@ }, "@ns:com:here:xyz": { "tags": [ - "xyz_source_id_COM_1000001_20240214" + "xyz_source_id_com_1000001_20240214" ] }, "speedLimit": "30", diff --git a/here-naksha-app-service/src/jvmTest/resources/unit_test_data/DefaultViewHandler/TC5032_patchFeature/feature_response_part.json b/here-naksha-app-service/src/jvmTest/resources/unit_test_data/DefaultViewHandler/TC5032_patchFeature/feature_response_part.json index d12471e30..3b1d33ac1 100644 --- a/here-naksha-app-service/src/jvmTest/resources/unit_test_data/DefaultViewHandler/TC5032_patchFeature/feature_response_part.json +++ b/here-naksha-app-service/src/jvmTest/resources/unit_test_data/DefaultViewHandler/TC5032_patchFeature/feature_response_part.json @@ -24,7 +24,7 @@ }, "@ns:com:here:xyz": { "tags": [ - "xyz_source_id_COM_1000001_20240214" + "xyz_source_id_com_1000001_20240214" ] }, "speedLimit": "20", diff --git a/here-naksha-app-service/src/jvmTest/resources/unit_test_data/PatchOnViewWithHttpStorage/TC01_patchFeatureOnlyInBase/response_body_part.json b/here-naksha-app-service/src/jvmTest/resources/unit_test_data/PatchOnViewWithHttpStorage/TC01_patchFeatureOnlyInBase/response_body_part.json index 72a4cfe81..95512d7bb 100644 --- a/here-naksha-app-service/src/jvmTest/resources/unit_test_data/PatchOnViewWithHttpStorage/TC01_patchFeatureOnlyInBase/response_body_part.json +++ b/here-naksha-app-service/src/jvmTest/resources/unit_test_data/PatchOnViewWithHttpStorage/TC01_patchFeatureOnlyInBase/response_body_part.json @@ -15,7 +15,7 @@ "@ns:com:here:xyz": { "action": "CREATE", "tags": [ - "xyz_source_id_COM_1000001_20240301" + "xyz_source_id_com_1000001_20240301" ] }, "speedLimit": "40", diff --git a/here-naksha-app-service/src/jvmTest/resources/unit_test_data/PatchOnViewWithHttpStorage/TC02_patchFeatureOnlyInDelta/response_body_part.json b/here-naksha-app-service/src/jvmTest/resources/unit_test_data/PatchOnViewWithHttpStorage/TC02_patchFeatureOnlyInDelta/response_body_part.json index 1548e1794..91cb7d56a 100644 --- a/here-naksha-app-service/src/jvmTest/resources/unit_test_data/PatchOnViewWithHttpStorage/TC02_patchFeatureOnlyInDelta/response_body_part.json +++ b/here-naksha-app-service/src/jvmTest/resources/unit_test_data/PatchOnViewWithHttpStorage/TC02_patchFeatureOnlyInDelta/response_body_part.json @@ -13,7 +13,7 @@ "action": "UPDATE", "tags": [ "one", - "xyz_source_id_COM_1000001_20240301" + "xyz_source_id_com_1000001_20240301" ] }, "speedLimit": "10", diff --git a/here-naksha-app-service/src/jvmTest/resources/unit_test_data/SourceHandlerId/TC2000_createFeatureWithoutTag/feature_response_part.json b/here-naksha-app-service/src/jvmTest/resources/unit_test_data/SourceHandlerId/TC2000_createFeatureWithoutTag/feature_response_part.json index d3019b3e6..773ad5628 100644 --- a/here-naksha-app-service/src/jvmTest/resources/unit_test_data/SourceHandlerId/TC2000_createFeatureWithoutTag/feature_response_part.json +++ b/here-naksha-app-service/src/jvmTest/resources/unit_test_data/SourceHandlerId/TC2000_createFeatureWithoutTag/feature_response_part.json @@ -15,7 +15,7 @@ "properties": { "@ns:com:here:xyz": { "tags": [ - "xyz_source_id_Task_1" + "xyz_source_id_task_1" ] }, "speedLimit": "50", diff --git a/here-naksha-app-service/src/jvmTest/resources/unit_test_data/SourceHandlerId/TC2001_createFeatureWithTag/feature_response_part.json b/here-naksha-app-service/src/jvmTest/resources/unit_test_data/SourceHandlerId/TC2001_createFeatureWithTag/feature_response_part.json index fdbe7d32b..1eb464489 100644 --- a/here-naksha-app-service/src/jvmTest/resources/unit_test_data/SourceHandlerId/TC2001_createFeatureWithTag/feature_response_part.json +++ b/here-naksha-app-service/src/jvmTest/resources/unit_test_data/SourceHandlerId/TC2001_createFeatureWithTag/feature_response_part.json @@ -16,7 +16,7 @@ "@ns:com:here:xyz": { "tags": [ "existing_normalized_tag", - "xyz_source_id_Task_3" + "xyz_source_id_task_3" ] }, "speedLimit": "50", From 359be6fe9df7ba860c01bae0bfcfe6b000274e04 Mon Sep 17 00:00:00 2001 From: Alexander Lowey-Weber Date: Fri, 4 Sep 2026 12:47:27 +0200 Subject: [PATCH 34/41] Fix that only sourceID_ has special treatment. Signed-off-by: Alexander Lowey-Weber --- .../kotlin/naksha/model/TagNormalizer.kt | 51 ++++++++++++------- 1 file changed, 32 insertions(+), 19 deletions(-) diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TagNormalizer.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TagNormalizer.kt index 5bcc97146..1c891d895 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TagNormalizer.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TagNormalizer.kt @@ -10,31 +10,44 @@ import kotlin.js.JsExport import kotlin.jvm.JvmStatic /** - * An object used for Tag normalization and splitting. + * An object used for Tag normalization and _(optional)_ splitting. * * Process of normalization happens in [normalizeTag] method and includes following steps: - * 1) Always: apply normalization form (see [NormalizerForm]) - * 2) Conditional: lowercase the whole tag + * + * 1) Always: apply [UNICODE normalization form](https://www.unicode.org/reports/tr15/) (see [NormalizerForm]) + * 2) Conditional: lowercase the tag * 3) Conditional: remove all non-ASCII characters + * 4) Optional: split + * + * Process of splitting tags is done when [TagList.toTagMap] is invoked. Note that not all tags can be split, it depends on their prefix. + * + * Summarised per-prefix behavior of the tag-normalization: * - * Normalization form used in step #1 and subsequent conditional steps depend on tag prefix. + * - `sourceID_.*` —> NFKC + * - **lowercase**: `false`, **ASCII**: `false`, **split**: `false` + * - `ref_.*` —> NFKC, reference + * - **lowercase**: `false`, **ASCII**: `false`, **split**: `false` + * - `@.*` —> NFKC, splittable reference + * - **lowercase**: `false`, **ASCII**: `false`, **split**: `true` + * - `#.*` —> NFD, + * - **lowercase**: `false`, **ASCII**: `true`, **split**: `true` + * - `~.*` —> NFD _(Web-URL friend variant of `#`)_ + * - **lowercase**: `false`, **ASCII**: `true`, **split**: `true` + * - otherwise: NFD + * - **lowercase**: `true`, **ASCII**: `true`, **split**: `true` * - * Process of splitting happens in [splitNormalizedTag] method. - * Note that not all tags can be split, it depends on their prefix. + * Note, the `sourceID_.*` is a historic artifact, it was the first exception being made from normalization. In the aftermath of this, rules were introduced, specifically the `ref_.*` and `@.*` rule, to avoid more exceptions. * - * Summarised per-prefix behavior: - * +----------+------------+-----------+----------+-------+ - * | prefix | norm. form | lowercase | no ASCII | split | - * +----------+------------+-----------+----------+-------+ - * | @ | NFKC | false | false | true | - * | ref_ | NFKC | false | false | false | - * | ~ | NFD | false | true | true | - * | # | NFD | false | true | true | - * | sourceID | NFKC | false | false | false | - * | < ELSE > | NFD | true | true | true | - * +----------+------------+-----------+----------+-------+ + * By default, (if no special prefix is found) tag is normalized with NFD, lowercased, cleaned of non-ASCII and is splittable. * - * By default, (if no special prefix is found) tag is normalized with NFD, lowercased, cleaned of non-ASCII and splittable. + * If you you copy identifiers into tags, it is strongly recommended to use the `@` _(at)_ prefix. For example `@sourceId=Ref$1`. This keeps the tag unchanged and allows to query for that exact tag, plus it allows to split the tags in code to tests if there is a `sourceId`: + * ```kotlin + * val tagList = TagList("@sourceId=Ref$1") + * val tagMap = tagList.toTagMap() + * println( tagMap.containsKey("@sourceId") ) + * println( tagMap.get("@sourceId") ) + * ``` + * @since 3.0 */ @JsExport class TagNormalizer private constructor() { @@ -44,7 +57,7 @@ class TagNormalizer private constructor() { private val PREFIX_TO_POLICY = mapOf( "@" to TagProcessingPolicy(NFKC, removeNonAscii = false, lowercase = false, split = true), "ref_" to TagProcessingPolicy(NFKC, removeNonAscii = false, lowercase = false, split = false), - "sourceID" to TagProcessingPolicy(NFKC, removeNonAscii = false, lowercase = false, split = false), + "sourceID_" to TagProcessingPolicy(NFKC, removeNonAscii = false, lowercase = false, split = false), "~" to TagProcessingPolicy(NFD, removeNonAscii = true, lowercase = false, split = true), "#" to TagProcessingPolicy(NFD, removeNonAscii = true, lowercase = false, split = true) ) From f67ec7e4e2cc6e22af1c5501a145371ac4c8a6d4 Mon Sep 17 00:00:00 2001 From: Alexander Lowey-Weber Date: Fri, 4 Sep 2026 12:47:53 +0200 Subject: [PATCH 35/41] Fix bug in value iteration, added tests for sourceID_ and at tags. Signed-off-by: Alexander Lowey-Weber --- .../commonMain/kotlin/naksha/base/MapProxy.kt | 77 +++++++++++-------- .../commonMain/kotlin/naksha/model/TagList.kt | 32 +++++--- .../kotlin/naksha/model/TagMapTest.kt | 24 ++++++ 3 files changed, 92 insertions(+), 41 deletions(-) diff --git a/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/MapProxy.kt b/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/MapProxy.kt index c72971fd5..59060847a 100644 --- a/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/MapProxy.kt +++ b/here-naksha-lib-base/src/commonMain/kotlin/naksha/base/MapProxy.kt @@ -167,40 +167,62 @@ open class MapProxy(val keyKlass: KClass, val valueKlas */ open fun toValue(key: K, value: Any?, alt: V? = null): V? = box(value, valueKlass, alt) + override val size: Int + get() = map_size(platformObject()) + override val entries: MutableSet> get() { - val basicEntries: MutableSet> = rawEntries() - .map { platformList -> - require(array_get_length(platformList) == 2) { "Expected PlatformList with size of 2 (key and value)" } - val key = toKey(array_get(platformList, 0)) - requireNotNull(key) { "Key can't be null" } - Entry(key, toValue(key, array_get(platformList, 1)), this) - } - .toMutableSet() - return MapProxyEntrySet(basicEntries, this) + val platformObject = platformObject() + val size = map_size(platformObject) + val it = map_iterator(platformObject) + var result: PlatformIteratorResult? = null + val entries = Array>(size) { i -> + result = it.next() + val entry = result.value + require(array_get_length(entry) == 2) { "Key $i can't be null" } + val key = toKey(array_get(entry, 0)) + requireNotNull(key) { "Key $i can't be null" } + val value = toValue(key, array_get(entry, 1)) + Entry(key, value, this) + } + return MapProxyEntrySet(entries.toMutableSet(), this) } override val keys: MutableSet get() { - return rawEntries() - .mapNotNull { platformList -> - require(array_get_length(platformList) == 2) { "Expected PlatformList with size of 2 (key and value)" } - toKey(array_get(platformList, 0)) - } - .toMutableSet() + val platformObject = platformObject() + val size = map_size(platformObject) + val it = map_iterator(platformObject) + var result: PlatformIteratorResult? = null + val keys = Array(size) { i -> + result = it.next() + val entry = result.value + require(array_get_length(entry) == 2) { "Key $i can't be null" } + val key = toKey(array_get(entry, 0)) + requireNotNull(key) { "Key $i can't be null" } + key as Any + } + @Suppress("UNCHECKED_CAST") + return keys.toMutableSet() as MutableSet } - override val size: Int - get() = map_size(platformObject()) - override val values: MutableCollection get() { - return rawEntries() - .mapNotNull { platformList -> - require(array_get_length(platformList) == 2) { "Expected PlatformList with size of 2 (key and value)" } - box(array_get(platformList, 1), valueKlass) - } - .toMutableSet() + val platformObject = platformObject() + val size = map_size(platformObject) + val it = map_iterator(platformObject) + var result: PlatformIteratorResult? = null + val values = Array(size) { i -> + result = it.next() + val entry = result.value + require(array_get_length(entry) == 2) { "Key $i can't be null" } + val key = toKey(array_get(entry, 0)) + requireNotNull(key) { "Key $i can't be null" } + val value = toValue(key, array_get(entry, 1)) + value as Any? + } + @Suppress("UNCHECKED_CAST") + return values.toMutableList() as MutableCollection } override fun clear() = map_clear(platformObject()) @@ -310,11 +332,4 @@ open class MapProxy(val keyKlass: KClass, val valueKlas ) } } - - private fun rawEntries(): Sequence { - val platformIterator = map_iterator(platformObject()) - return generateSequence(platformIterator.next().value) { - platformIterator.next().value - } - } } diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TagList.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TagList.kt index 7acb2be24..f70633823 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TagList.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TagList.kt @@ -14,6 +14,8 @@ import kotlin.jvm.JvmStatic /** * A list of tags. + * @see TagNormalizer + * @since 3.0 */ @JsExport class TagList() : StringList(), ITagList { @@ -22,6 +24,7 @@ class TagList() : StringList(), ITagList { * Create a tag list from the given arguments; the tags are normalized. * @param tags the tags. * @param skipNormalize if normalization should be skipped; expects then that the given values are already normalized. + * @since 3.0 */ @JvmOverloads @JsName("of") @@ -36,6 +39,7 @@ class TagList() : StringList(), ITagList { * @param skipInvalid if invalid values in the given should be skipped; otherwise an exception is raised. * @param skipNormalize if normalization should be skipped; expects then that the given values are already normalized. * @throws naksha.base.NakshaException with error [ILLEGAL_ARGUMENT][naksha.base.NakshaError.ILLEGAL_ARGUMENT] if the given list contains `null` or valus not being `String` and [skipInvalid] is _false_. + * @since 3.0 */ @JvmOverloads @JsName("ofList") @@ -50,11 +54,12 @@ class TagList() : StringList(), ITagList { } /** - * Returns 'true' if the tag was removed, 'false' if it was not present. + * Returns _true_ if the tag was removed, _false_ if it was not present. * * @param tag The normalized tag to remove. - * @param normalize `true` if the tag should be normalized before trying to remove; `false` if the tag is normalized. + * @param normalize _true_ if the tag should be normalized before trying to remove; _false_ if the tag is normalized. * @return true if the tag was removed; false otherwise. + * @since 3.0 */ fun removeTag(tag: String, normalize: Boolean): Boolean { val tagToRemove = if (normalize) normalizeTag(tag) else tag @@ -65,8 +70,9 @@ class TagList() : StringList(), ITagList { * Removes the given tags. * * @param tags The tags to remove. - * @param normalize `true` if the tags should be normalized before trying to remove; `false` if the tags are normalized. + * @param normalize _true_ if the tags should be normalized before trying to remove; _false_ if the tags are normalized. * @return this. + * @since 3.0 */ fun removeTags(tags: List?, normalize: Boolean): TagList { if (tags.isNullOrEmpty()) { @@ -86,8 +92,9 @@ class TagList() : StringList(), ITagList { /** * Removes tags starting with prefix * - * @param prefix string prefix. + * @param prefix string prefix _(must be normalized)_. * @return this. + * @since 3.0 */ fun removeTagsWithPrefix(prefix: String?): TagList { if (isEmpty() || prefix == null) { @@ -99,10 +106,11 @@ class TagList() : StringList(), ITagList { } /** - * Removes tags starting with given list of prefixes + * Removes tags starting with given list of prefixes. * - * @param prefixes list of tag prefixes + * @param prefixes list of tag prefixes _(must be normalized)_. * @return this. + * @since 3.0 */ fun removeTagsWithPrefixes(prefixes: List?): TagList { if (prefixes != null) { @@ -114,11 +122,11 @@ class TagList() : StringList(), ITagList { } /** - * Returns 'true' if the tag added, 'false' if it was already present. + * Returns _true_ if the tag added, _false_ if it was already present. * * @param tag the tag to add. - * @param normalize `true` if the tag should be normalized; `false` otherwise. - * @return true if the tag added; false otherwise. + * @param normalize defaults to _true_; set to _false_ only if the tag is already normalized. + * @since 3.0 */ fun addTag(tag: String, normalize: Boolean = true): Boolean { val tagToAdd = if (normalize) normalizeTag(tag) else tag @@ -134,8 +142,9 @@ class TagList() : StringList(), ITagList { * Add the given tags. * * @param tags the tags to add. - * @param normalize `true` if the given tags should be normalized; `false`, if they are already normalized. + * @param normalize defaults to _true_; set to _false_ only if the tags are already normalized. * @return this. + * @since 3.0 */ fun addTags(tags: List?, normalize: Boolean = true): TagList { if (!tags.isNullOrEmpty()) { @@ -158,6 +167,7 @@ class TagList() : StringList(), ITagList { * * @param tags the tags to normalize and add. * @return this. + * @since 3.0 */ fun addAndNormalizeTags(vararg tags: String): TagList { if (tags.isNotEmpty()) { @@ -175,6 +185,7 @@ class TagList() : StringList(), ITagList { /** * Convert this tag-list into a tag-map. * @return this tag-list as tag-map. + * @since 3.0 */ fun toTagMap(): TagMap = TagMap(this) @@ -206,6 +217,7 @@ class TagList() : StringList(), ITagList { * * @param tags a list of tags. * @return the same list, just that the content is normalized. + * @since 3.0 */ @JvmStatic @JsStatic diff --git a/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/TagMapTest.kt b/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/TagMapTest.kt index eeadaa1a2..3a31e9c39 100644 --- a/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/TagMapTest.kt +++ b/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/TagMapTest.kt @@ -55,5 +55,29 @@ class TagMapTest { assertEquals("Tag values can only be String, Boolean or Number", failure.message) } + @Test + fun shouldAllowToSplitReferences() { + val tagList = TagList("@sourceId=Ref\$1") + assertEquals(1, tagList.size) + val tagMap = tagList.toTagMap() + assertEquals(1, tagMap.size) + assertTrue(tagMap.containsKey("@sourceId")) + assertEquals("Ref\$1", tagMap["@sourceId"]) + assertEquals("@sourceId", tagMap.keys.first()) + assertEquals("Ref\$1", tagMap.values.first()) + } + + @Test + fun shouldSupportSourceID() { + val tagList = TagList("sourceID_Ref\$1") + assertEquals(1, tagList.size) + val tagMap = tagList.toTagMap() + assertEquals(1, tagMap.size) + assertTrue(tagMap.containsKey("sourceID_Ref\$1")) + assertNull(tagMap["sourceID_Ref\$1"]) + assertEquals("sourceID_Ref\$1", tagMap.keys.first()) + assertNull(tagMap.values.first()) + } + object NotSupportedType } \ No newline at end of file From c3f282e3919212b476a429361e5dfbe40e707997 Mon Sep 17 00:00:00 2001 From: Alexander Lowey-Weber Date: Mon, 7 Sep 2026 15:00:28 +0200 Subject: [PATCH 36/41] Restore tests to original casing. Signed-off-by: Alexander Lowey-Weber --- .../com/here/naksha/app/service/SourceIdHandlerApiTest.java | 1 - .../TC5030_patchFeature/feature_response_part.json | 2 +- .../TC5031_patchFeature/feature_response_part.json | 2 +- .../TC5032_patchFeature/feature_response_part.json | 2 +- .../TC01_patchFeatureOnlyInBase/response_body_part.json | 2 +- .../TC02_patchFeatureOnlyInDelta/response_body_part.json | 2 +- .../TC2000_createFeatureWithoutTag/feature_response_part.json | 2 +- .../TC2001_createFeatureWithTag/feature_response_part.json | 2 +- 8 files changed, 7 insertions(+), 8 deletions(-) diff --git a/here-naksha-app-service/src/jvmTest/java/com/here/naksha/app/service/SourceIdHandlerApiTest.java b/here-naksha-app-service/src/jvmTest/java/com/here/naksha/app/service/SourceIdHandlerApiTest.java index a8d00d88d..8e7f8dc48 100644 --- a/here-naksha-app-service/src/jvmTest/java/com/here/naksha/app/service/SourceIdHandlerApiTest.java +++ b/here-naksha-app-service/src/jvmTest/java/com/here/naksha/app/service/SourceIdHandlerApiTest.java @@ -31,7 +31,6 @@ static void setup() throws URISyntaxException, IOException, InterruptedException nakshaClient.post("hub/spaces/" + SPACE_ID + "/features", initialFeaturesJson, UUID.randomUUID().toString()); } - @Test void tc2000_testCreateFeaturesWithSourceIdInMeta() throws Exception { // Given: diff --git a/here-naksha-app-service/src/jvmTest/resources/unit_test_data/DefaultViewHandler/TC5030_patchFeature/feature_response_part.json b/here-naksha-app-service/src/jvmTest/resources/unit_test_data/DefaultViewHandler/TC5030_patchFeature/feature_response_part.json index a79c06c11..96e980819 100644 --- a/here-naksha-app-service/src/jvmTest/resources/unit_test_data/DefaultViewHandler/TC5030_patchFeature/feature_response_part.json +++ b/here-naksha-app-service/src/jvmTest/resources/unit_test_data/DefaultViewHandler/TC5030_patchFeature/feature_response_part.json @@ -24,7 +24,7 @@ }, "@ns:com:here:xyz": { "tags": [ - "xyz_source_id_com_1000001_20240214" + "xyz_source_id_COM_1000001_20240214" ] }, "speedLimit": "50", diff --git a/here-naksha-app-service/src/jvmTest/resources/unit_test_data/DefaultViewHandler/TC5031_patchFeature/feature_response_part.json b/here-naksha-app-service/src/jvmTest/resources/unit_test_data/DefaultViewHandler/TC5031_patchFeature/feature_response_part.json index 41def6499..973545ffb 100644 --- a/here-naksha-app-service/src/jvmTest/resources/unit_test_data/DefaultViewHandler/TC5031_patchFeature/feature_response_part.json +++ b/here-naksha-app-service/src/jvmTest/resources/unit_test_data/DefaultViewHandler/TC5031_patchFeature/feature_response_part.json @@ -24,7 +24,7 @@ }, "@ns:com:here:xyz": { "tags": [ - "xyz_source_id_com_1000001_20240214" + "xyz_source_id_COM_1000001_20240214" ] }, "speedLimit": "30", diff --git a/here-naksha-app-service/src/jvmTest/resources/unit_test_data/DefaultViewHandler/TC5032_patchFeature/feature_response_part.json b/here-naksha-app-service/src/jvmTest/resources/unit_test_data/DefaultViewHandler/TC5032_patchFeature/feature_response_part.json index 3b1d33ac1..d12471e30 100644 --- a/here-naksha-app-service/src/jvmTest/resources/unit_test_data/DefaultViewHandler/TC5032_patchFeature/feature_response_part.json +++ b/here-naksha-app-service/src/jvmTest/resources/unit_test_data/DefaultViewHandler/TC5032_patchFeature/feature_response_part.json @@ -24,7 +24,7 @@ }, "@ns:com:here:xyz": { "tags": [ - "xyz_source_id_com_1000001_20240214" + "xyz_source_id_COM_1000001_20240214" ] }, "speedLimit": "20", diff --git a/here-naksha-app-service/src/jvmTest/resources/unit_test_data/PatchOnViewWithHttpStorage/TC01_patchFeatureOnlyInBase/response_body_part.json b/here-naksha-app-service/src/jvmTest/resources/unit_test_data/PatchOnViewWithHttpStorage/TC01_patchFeatureOnlyInBase/response_body_part.json index 95512d7bb..72a4cfe81 100644 --- a/here-naksha-app-service/src/jvmTest/resources/unit_test_data/PatchOnViewWithHttpStorage/TC01_patchFeatureOnlyInBase/response_body_part.json +++ b/here-naksha-app-service/src/jvmTest/resources/unit_test_data/PatchOnViewWithHttpStorage/TC01_patchFeatureOnlyInBase/response_body_part.json @@ -15,7 +15,7 @@ "@ns:com:here:xyz": { "action": "CREATE", "tags": [ - "xyz_source_id_com_1000001_20240301" + "xyz_source_id_COM_1000001_20240301" ] }, "speedLimit": "40", diff --git a/here-naksha-app-service/src/jvmTest/resources/unit_test_data/PatchOnViewWithHttpStorage/TC02_patchFeatureOnlyInDelta/response_body_part.json b/here-naksha-app-service/src/jvmTest/resources/unit_test_data/PatchOnViewWithHttpStorage/TC02_patchFeatureOnlyInDelta/response_body_part.json index 91cb7d56a..1548e1794 100644 --- a/here-naksha-app-service/src/jvmTest/resources/unit_test_data/PatchOnViewWithHttpStorage/TC02_patchFeatureOnlyInDelta/response_body_part.json +++ b/here-naksha-app-service/src/jvmTest/resources/unit_test_data/PatchOnViewWithHttpStorage/TC02_patchFeatureOnlyInDelta/response_body_part.json @@ -13,7 +13,7 @@ "action": "UPDATE", "tags": [ "one", - "xyz_source_id_com_1000001_20240301" + "xyz_source_id_COM_1000001_20240301" ] }, "speedLimit": "10", diff --git a/here-naksha-app-service/src/jvmTest/resources/unit_test_data/SourceHandlerId/TC2000_createFeatureWithoutTag/feature_response_part.json b/here-naksha-app-service/src/jvmTest/resources/unit_test_data/SourceHandlerId/TC2000_createFeatureWithoutTag/feature_response_part.json index 773ad5628..d3019b3e6 100644 --- a/here-naksha-app-service/src/jvmTest/resources/unit_test_data/SourceHandlerId/TC2000_createFeatureWithoutTag/feature_response_part.json +++ b/here-naksha-app-service/src/jvmTest/resources/unit_test_data/SourceHandlerId/TC2000_createFeatureWithoutTag/feature_response_part.json @@ -15,7 +15,7 @@ "properties": { "@ns:com:here:xyz": { "tags": [ - "xyz_source_id_task_1" + "xyz_source_id_Task_1" ] }, "speedLimit": "50", diff --git a/here-naksha-app-service/src/jvmTest/resources/unit_test_data/SourceHandlerId/TC2001_createFeatureWithTag/feature_response_part.json b/here-naksha-app-service/src/jvmTest/resources/unit_test_data/SourceHandlerId/TC2001_createFeatureWithTag/feature_response_part.json index 1eb464489..fdbe7d32b 100644 --- a/here-naksha-app-service/src/jvmTest/resources/unit_test_data/SourceHandlerId/TC2001_createFeatureWithTag/feature_response_part.json +++ b/here-naksha-app-service/src/jvmTest/resources/unit_test_data/SourceHandlerId/TC2001_createFeatureWithTag/feature_response_part.json @@ -16,7 +16,7 @@ "@ns:com:here:xyz": { "tags": [ "existing_normalized_tag", - "xyz_source_id_task_3" + "xyz_source_id_Task_3" ] }, "speedLimit": "50", From 8c85ea31ded36d2f0139f4ea39d25fdd09f716a5 Mon Sep 17 00:00:00 2001 From: Alexander Lowey-Weber Date: Mon, 7 Sep 2026 15:01:32 +0200 Subject: [PATCH 37/41] Make tag normalization optional, defaulting to none, adding normalize helper. Signed-off-by: Alexander Lowey-Weber --- .../commonMain/kotlin/naksha/model/TagList.kt | 89 ++++++++++++------- 1 file changed, 55 insertions(+), 34 deletions(-) diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TagList.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TagList.kt index f70633823..6cffac8f7 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TagList.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TagList.kt @@ -13,9 +13,10 @@ import kotlin.jvm.JvmOverloads import kotlin.jvm.JvmStatic /** - * A list of tags. - * @see TagNormalizer + * A list of strings called `Tag`. + * * @since 3.0 + * @see TagNormalizer */ @JsExport class TagList() : StringList(), ITagList { @@ -23,32 +24,32 @@ class TagList() : StringList(), ITagList { /** * Create a tag list from the given arguments; the tags are normalized. * @param tags the tags. - * @param skipNormalize if normalization should be skipped; expects then that the given values are already normalized. + * @param normalize if the given tags should be normalized. * @since 3.0 */ @JvmOverloads @JsName("of") - constructor(vararg tags: String, skipNormalize: Boolean = false): this() { + constructor(vararg tags: String, normalize: Boolean = false): this() { setCapacity(tags.size) - for (tag in tags) addTag(tag, !skipNormalize) + for (tag in tags) addTag(tag, normalize) } /** * Create a tag list from the given list; the tags are normalized. * @param tags the tags. * @param skipInvalid if invalid values in the given should be skipped; otherwise an exception is raised. - * @param skipNormalize if normalization should be skipped; expects then that the given values are already normalized. + * @param normalize if the given tags should be normalized. * @throws naksha.base.NakshaException with error [ILLEGAL_ARGUMENT][naksha.base.NakshaError.ILLEGAL_ARGUMENT] if the given list contains `null` or valus not being `String` and [skipInvalid] is _false_. * @since 3.0 */ @JvmOverloads @JsName("ofList") - constructor(tags: List<*>, skipInvalid: Boolean = false, skipNormalize: Boolean = false): this() { + constructor(tags: List<*>, skipInvalid: Boolean = false, normalize: Boolean = false): this() { setCapacity(tags.size) for (i in 0 until tags.size) { val tag = tags[i] - if (tag is String) addTag(tag, !skipNormalize) - else if (tag is Char || tag is CharSequence) addTag(tag.toString(), !skipNormalize) + if (tag is String) addTag(tag, normalize) + else if (tag is Char || tag is CharSequence) addTag(tag.toString(), normalize) else if (!skipInvalid) throw illegalArg("The tag $i is no string: $tag") } } @@ -56,12 +57,13 @@ class TagList() : StringList(), ITagList { /** * Returns _true_ if the tag was removed, _false_ if it was not present. * - * @param tag The normalized tag to remove. - * @param normalize _true_ if the tag should be normalized before trying to remove; _false_ if the tag is normalized. + * @param tag The tag to remove. + * @param normalize _true_ if the tag will be normalized before trying to remove; **false** otherwise, default. * @return true if the tag was removed; false otherwise. * @since 3.0 */ - fun removeTag(tag: String, normalize: Boolean): Boolean { + @JvmOverloads + fun removeTag(tag: String, normalize: Boolean = false): Boolean { val tagToRemove = if (normalize) normalizeTag(tag) else tag return this.remove(tagToRemove) } @@ -69,12 +71,13 @@ class TagList() : StringList(), ITagList { /** * Removes the given tags. * - * @param tags The tags to remove. - * @param normalize _true_ if the tags should be normalized before trying to remove; _false_ if the tags are normalized. + * @param tags the tags to remove. + * @param normalize _true_ if the tags will be normalized before trying to remove; **false** otherwise, default. * @return this. * @since 3.0 */ - fun removeTags(tags: List?, normalize: Boolean): TagList { + @JvmOverloads + fun removeTags(tags: List?, normalize: Boolean = false): TagList { if (tags.isNullOrEmpty()) { return this } @@ -92,15 +95,16 @@ class TagList() : StringList(), ITagList { /** * Removes tags starting with prefix * - * @param prefix string prefix _(must be normalized)_. + * @param prefix string prefix. + * @param normalize _true_ if the prefix will be normalized before trying to remove; **false** otherwise, default. * @return this. * @since 3.0 */ - fun removeTagsWithPrefix(prefix: String?): TagList { - if (isEmpty() || prefix == null) { - return this - } - val tagsToRemove = this.filter { tag -> tag?.startsWith(prefix) ?: false } + @JvmOverloads + fun removeTagsWithPrefix(prefix: String?, normalize: Boolean = false): TagList { + if (isEmpty() || prefix == null) return this + val normalizedPrefix = if (normalize) normalizeTag(prefix) else prefix + val tagsToRemove = this.filter { tag -> tag?.startsWith(normalizedPrefix) ?: false } removeAll(tagsToRemove) return this } @@ -108,15 +112,18 @@ class TagList() : StringList(), ITagList { /** * Removes tags starting with given list of prefixes. * - * @param prefixes list of tag prefixes _(must be normalized)_. + * @param prefixes list of tag prefixes. + * @param normalize _true_ if the prefixes should be normalized before trying to remove; **false** otherwise, default. * @return this. * @since 3.0 */ - fun removeTagsWithPrefixes(prefixes: List?): TagList { - if (prefixes != null) { - for (prefix in prefixes) { - if (prefix != null) removeTagsWithPrefix(prefix) - } + @JvmOverloads + fun removeTagsWithPrefixes(prefixes: List?, normalize: Boolean = false): TagList { + if (prefixes == null) return this + for (prefix in prefixes) { + if (prefix == null) continue + if (normalize) removeTagsWithPrefix(normalizeTag(prefix)) + else removeTagsWithPrefix(prefix) } return this } @@ -125,14 +132,15 @@ class TagList() : StringList(), ITagList { * Returns _true_ if the tag added, _false_ if it was already present. * * @param tag the tag to add. - * @param normalize defaults to _true_; set to _false_ only if the tag is already normalized. + * @param normalize defaults to _false_; set to _true_ if the tags should be normalized. * @since 3.0 */ - fun addTag(tag: String, normalize: Boolean = true): Boolean { - val tagToAdd = if (normalize) normalizeTag(tag) else tag + @JvmOverloads + fun addTag(tag: String, normalize: Boolean = false): Boolean { + val normalizedTag = if (normalize) normalizeTag(tag) else tag - if (!contains(tagToAdd)) { - add(tagToAdd) + if (!contains(normalizedTag)) { + add(normalizedTag) return true } return false @@ -142,11 +150,12 @@ class TagList() : StringList(), ITagList { * Add the given tags. * * @param tags the tags to add. - * @param normalize defaults to _true_; set to _false_ only if the tags are already normalized. + * @param normalize defaults to _false_; set to _true_ if the tags should be normalized. * @return this. * @since 3.0 */ - fun addTags(tags: List?, normalize: Boolean = true): TagList { + @JvmOverloads + fun addTags(tags: List?, normalize: Boolean = false): TagList { if (!tags.isNullOrEmpty()) { if (normalize) { for (s in tags) { @@ -181,6 +190,18 @@ class TagList() : StringList(), ITagList { return this } + /** + * Apply [TagNormalizer.normalizeTag] to all strings being in this list. + * @return this. + * @since 3.0 + */ + fun normalize(): TagList { + for (i in 0 until this.size) { + val tag = this[i] ?: continue + this[i] = normalizeTag(tag) + } + return this + } /** * Convert this tag-list into a tag-map. From 8045988a84dbeb634886181ff1fd983403e21176 Mon Sep 17 00:00:00 2001 From: Alexander Lowey-Weber Date: Mon, 7 Sep 2026 15:02:32 +0200 Subject: [PATCH 38/41] Improve constructors of TagMap, update documentation. Signed-off-by: Alexander Lowey-Weber --- .../commonMain/kotlin/naksha/model/TagMap.kt | 104 +++++++++++------- 1 file changed, 66 insertions(+), 38 deletions(-) diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TagMap.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TagMap.kt index f53f0fde7..1367fe1f8 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TagMap.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TagMap.kt @@ -2,33 +2,82 @@ package naksha.model -import naksha.base.ITagMap import naksha.base.MapProxy import naksha.base.NakshaError import naksha.base.NakshaException +import naksha.base.illegalArg +import naksha.model.TagNormalizer.TagNormalizer_C.joinTag +import naksha.model.TagNormalizer.TagNormalizer_C.splitTag import kotlin.js.JsExport import kotlin.js.JsName /** - * Map of tags persisted as (key, value) pairs where values are nullable. - * This class represents the persisted form of [TagList]. - * - * It is advised to only construct it in one of two ways: - * 1) Via [TagList]-based constructor - * 2) By deserializing bytes fetched from a storage - * - * If for some reason, one would like to use it otherwise, it is advised to properly prepare tags upfront - * with use of [TagNormalizer] (that is used for example by [TagList]) + * Map of tags with values as _(key, value)_ pairs. Beware that values are limited to the following primitives: + * - `null` + * - [Boolean] + * - [Double] + * - [String] + * @since 3.0 */ @JsExport -class TagMap() : MapProxy(String::class, Any::class), ITagMap { +class TagMap() : MapProxy(String::class, Any::class) { - @Suppress("LeakingThis") - @JsName("of") + /** + * Construct a new [TagMap] from the given list of key-value pairs. + * @param pairs a list of keys and values with the key being a [String] and the value being `null`, [Boolean], [Number] or [String]. + * @since 3.0 + * @throws NakshaException if the key is not a [String] or the value of any pair is not `null`, [Boolean], [Number] or [String]. + */ + @JsName("newTagMap") + constructor(vararg pairs: Any?) : this() { + var i = 0 + while (i < pairs.size) { + val key: String = pairs[i] as? String? ?: throw illegalArg("The given key at $i is no String: ${pairs[i]}") + val value = if (++i < pairs.size) when(val v = pairs[i++]) { + null -> null + is Boolean -> v + is String -> v + is Double -> v + is Number -> v.toDouble() + else -> throw illegalArg("The given value is not boolean, a number or a string: $v") + } else null + i++ + this[key] = value + } + } + + /** + * Construct a new [TagMap] from the given list of key-value pairs. + * @param tags the key-value pairs. + * @since 3.0 + * @throws NakshaException if the value of any pair is not `null`, [Boolean], [Number] or [String]. + */ + @JsName("ofPairs") + constructor(vararg tags: Pair) : this() { + for ((k, v) in tags) { + this[k] = when (v) { + null -> null + is Boolean -> v + is String -> v + is Double -> v + is Number -> v.toDouble() + else -> throw illegalArg("The given value is not boolean, a number or a string: $v") + } + } + } + + /** + * Construct a [TagMap] from the given [TagList]. + * @param tagList the [TagList] to split and insert into this map. + * @since 3.0 + */ + @JsName("ofTagList") constructor(tagList: TagList) : this() { - tagList.filterNotNull() - .map { TagNormalizer.splitNormalizedTag(it) } - .forEach { (key, value) -> put(key, value) } + for (tag in tagList) { + if (tag == null) continue + val pair = splitTag(tag) + put(pair.first, pair.second) + } } /** @@ -37,28 +86,7 @@ class TagMap() : MapProxy(String::class, Any::class), ITagMap { */ fun toTagList(): TagList { val list = TagList() - forEach { (key, value) -> - list.add(flattenTag(key, value)) - } + forEach { (key, value) -> list.add(joinTag(key, value)) } return list } - - /** - * Converts (key, value) pair to String, so it can be part of [TagList]. - * The result depends on the value: - * - Null value is omitted: ('foo', null) -> 'foo' - * - String value is separated with simple '=': ('foo', 'bar') -> 'foo=bar' - * - Numbers and booleans are separated with ':=' -> 'foo:=true', 'foo:=12.34' - */ - private fun flattenTag(key: String, value: Any?): String = - when (value) { - null -> key - is String -> "$key=$value" - is Boolean, is Long, is Int64 -> "$key:=$value" - is Number -> "$key:=${value.toDouble()}" - else -> throw NakshaException( - NakshaError.ILLEGAL_ARGUMENT, - "Tag values can only be String, Boolean or Number" - ) - } } From 9f6bace6e071906fdac0d498a7f86d8533883c51 Mon Sep 17 00:00:00 2001 From: Alexander Lowey-Weber Date: Mon, 7 Sep 2026 15:03:05 +0200 Subject: [PATCH 39/41] Remove renamed skipNormalize parameter, is now normalize. Signed-off-by: Alexander Lowey-Weber --- .../src/commonTest/kotlin/naksha/model/XyzProxyTest.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/XyzProxyTest.kt b/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/XyzProxyTest.kt index 13aafec3f..9c7e2ad0e 100644 --- a/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/XyzProxyTest.kt +++ b/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/XyzProxyTest.kt @@ -154,7 +154,7 @@ class XyzProxyTest { val xyz = XyzNs() // when - xyz.setTags(TagList("Alicja", "Baba", "Alan", skipNormalize = true), normalize = false) + xyz.setTags(TagList("Alicja", "Baba", "Alan"), normalize = false) // then assertEquals(listOf("Alicja", "Baba", "Alan"), xyz.tags.toList()) From 531171c97e0a013a9b2eadbe700f9a6aab342933 Mon Sep 17 00:00:00 2001 From: Alexander Lowey-Weber Date: Mon, 7 Sep 2026 15:04:34 +0200 Subject: [PATCH 40/41] Improve normalizer, use last equals for split instead of first, added join method. Improve tests to match fixes. Signed-off-by: Alexander Lowey-Weber --- .../kotlin/naksha/model/TagNormalizer.kt | 94 +++++++++++++------ .../kotlin/naksha/model/TagNormalizerTest.kt | 43 +++++++-- 2 files changed, 102 insertions(+), 35 deletions(-) diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TagNormalizer.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TagNormalizer.kt index 1c891d895..96cb69fa6 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TagNormalizer.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TagNormalizer.kt @@ -1,12 +1,13 @@ package naksha.model +import naksha.base.NakshaException import naksha.base.NormalizerForm import naksha.base.NormalizerForm.NFD import naksha.base.NormalizerForm.NFKC import naksha.base.Platform -import naksha.model.TagNormalizer.TagNormalizer_C.normalizeTag -import naksha.model.TagNormalizer.TagNormalizer_C.splitNormalizedTag +import naksha.base.illegalArg import kotlin.js.JsExport +import kotlin.js.JsStatic import kotlin.jvm.JvmStatic /** @@ -56,9 +57,11 @@ class TagNormalizer private constructor() { private val DEFAULT_POLICY = TagProcessingPolicy(NFD, removeNonAscii = true, lowercase = true, split = true) private val PREFIX_TO_POLICY = mapOf( "@" to TagProcessingPolicy(NFKC, removeNonAscii = false, lowercase = false, split = true), + "~" to TagProcessingPolicy(NFD, removeNonAscii = true, lowercase = false, split = true), + // Downward compatibility workarounds: "ref_" to TagProcessingPolicy(NFKC, removeNonAscii = false, lowercase = false, split = false), "sourceID_" to TagProcessingPolicy(NFKC, removeNonAscii = false, lowercase = false, split = false), - "~" to TagProcessingPolicy(NFD, removeNonAscii = true, lowercase = false, split = true), + "xyz_source_id_" to TagProcessingPolicy(NFKC, removeNonAscii = false, lowercase = false, split = false), "#" to TagProcessingPolicy(NFD, removeNonAscii = true, lowercase = false, split = true) ) @@ -66,7 +69,11 @@ class TagNormalizer private constructor() { private val TO_LOWER: CharArray = CharArray(128 - 32) { (it + 32).toChar().lowercaseChar() } /** - * Main method for raw tag normalization. See[TagNormalizer] doc for more + * Normalize the given tag using the [tag-normalization rules][TagNormalizer]. + * @param tag the tag. + * @return the normalized tag, see [TagNormalizer]. + * @see TagNormalizer + * @since 3.0 */ @JvmStatic fun normalizeTag(tag: String): String { @@ -98,37 +105,68 @@ class TagNormalizer private constructor() { /** - * Main method for normalized tag splitting. See[TagNormalizer] doc for more + * Split a tag at the last equal sign (`=`). + * + * If the equal sign is preceded by a colon (`:`) the value is parsed into `Boolean`, or `Double` with a fallback to [String]. + * @param tag the tag to split. + * @return the _key_ and _value_, with _value_ potentially being `null`. + * @since 3.0 */ - internal fun splitNormalizedTag(normalizedTag: String): Pair { - if (!policyFor(normalizedTag).split) { - return normalizedTag to null + @JsStatic + @JvmStatic + fun splitTag(tag: String): Pair { + if (!policyFor(tag).split) { + return tag to null } - val i = normalizedTag.indexOf('=') - val key: String - val value: Any? - if (i >= 1) { - if (normalizedTag[i - 1] == ':') { // := - key = normalizedTag.substring(0, i - 1).trim() - val raw = normalizedTag.substring(i + 1).trim() - value = if ("true".equals(raw, ignoreCase = true)) { - true - } else if ("false".equals(raw, ignoreCase = true)) { - false - } else { - raw.toDouble() - } - } else { - key = normalizedTag.substring(0, i).trim() - value = normalizedTag.substring(i + 1).trim() + val pos = tag.lastIndexOf('=') + if (pos < 1) return tag to null + if (tag[pos - 1] == ':') { // := + val key = tag.substring(0, pos - 1).trim() + val raw = tag.substring(pos + 1).trim() + if ("true".equals(raw, ignoreCase = true)) return key to true + if ("false".equals(raw, ignoreCase = true)) return key to false + return try { + key to raw.toDouble() + } catch (_: NumberFormatException) { + // This is an illegal tag encoding, we do not split + tag to raw } - } else { - key = normalizedTag - value = null } + // Assignment failed, use equals. + val key = tag.substring(0, pos).trim() + val value = tag.substring(pos + 1).trim() return key to value } + /** + * Converts _(key, value)_ pair to String, so it can be part of [TagList]. + * + * The result depends on the value: + * - `null` — value is omitted + * - (`"foo"`, `null`) —> `"foo"` + * - [String] — value is separated with equal sign (`=`) + * - (`"foo"`, `"bar"`) -> `"foo=bar"` + * - [Boolean] or [Number] – value is separated with colon-equal (`:=`) + * - (`"foo"`, `12.34`) —> `"foo:=12.34"` + * - (`"foo"`, `true`) —> `"foo:=true"` + * + * @param key the key to join. + * @param value the value to join. + * @return the stringified tag. + * @throws NakshaException with error [ILLEGAL_ARGUMENT][naksha.base.NakshaError.ILLEGAL_ARGUMENT] if the given value is not `null`, [String], [Boolean] or [Number]. + * @since 3.0 + */ + @JsStatic + @JvmStatic + fun joinTag(key: String, value: Any?): String = + when (value) { + null -> key + is String -> "$key=$value" + is Boolean, is Long -> "$key:=$value" + is Number -> "$key:=${value.toDouble()}" + else -> throw illegalArg("Tag values can only be String, Boolean or Number, found: $value") + } + private fun policyFor(tag: String): TagProcessingPolicy { for ((prefix, policy) in PREFIX_TO_POLICY) { if (tag.startsWith(prefix)) return policy diff --git a/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/TagNormalizerTest.kt b/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/TagNormalizerTest.kt index 503d7524b..fdeedf2c6 100644 --- a/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/TagNormalizerTest.kt +++ b/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/TagNormalizerTest.kt @@ -1,5 +1,8 @@ package naksha.model +import naksha.model.TagNormalizer.TagNormalizer_C.joinTag +import naksha.model.TagNormalizer.TagNormalizer_C.normalizeTag +import naksha.model.TagNormalizer.TagNormalizer_C.splitTag import kotlin.test.Test import kotlin.test.assertEquals @@ -23,7 +26,7 @@ class TagNormalizerTest { val tagsWithAsciiToBePreserved = listOf( "@p®¡©e=100£", // starting with '@' "ref_p®¡©e=100£", // starting with 'ref_' - "sourceIDp®¡©e=100£", // starting with 'sourceID' + "sourceID_p®¡©e=100£", // starting with 'sourceID' ) tagsWithAsciiToBePreserved.forEach { tag -> @@ -44,7 +47,7 @@ class TagNormalizerTest { "ref_Some_Tag:=1235", "~Some_Tag:=1235", "#Some_Tag:=1235", - "sourceIDSome_Tag:=1235" + "sourceID_Some_Tag:=1235" ) tagsNotToBeLowercased.forEach { tag -> @@ -63,24 +66,35 @@ class TagNormalizerTest { tagsToBeSplit.forEach { rawTag -> val expectedKey = rawTag.split(":")[0] - val normalized = TagNormalizer.normalizeTag(rawTag) - val (tagKey, tagValue) = TagNormalizer.splitNormalizedTag(normalized) + val normalized = normalizeTag(rawTag) + val (tagKey, tagValue) = splitTag(normalized) assertEquals(expectedKey, tagKey) assertEquals(1235.0, tagValue) } + + run { + val (key, value) = splitTag("some_tag:==1235") + assertEquals("some_tag:=", key) + assertEquals("1235", value) + } + run { + val (key, value) = splitTag("some_tag==:=1235") + assertEquals("some_tag==", key) + assertEquals(1235.0, value) + } } @Test fun shouldNotSplit() { val tagsNotToBeSplit = listOf( "ref_some_tag:=1235", - "sourceIDsome_tag:=1235" + "sourceID_some_tag:=1235" ) tagsNotToBeSplit.forEach { rawTag -> val normalized = TagNormalizer.normalizeTag(rawTag) - val (tagKey, tagValue) = TagNormalizer.splitNormalizedTag(normalized) + val (tagKey, tagValue) = splitTag(normalized) assertEquals(rawTag, tagKey) assertEquals(null, tagValue) @@ -96,10 +110,25 @@ class TagNormalizerTest { val normalized = TagNormalizer.normalizeTag(tagToBeSplit) // And: - val (key, value) = TagNormalizer.splitNormalizedTag(normalized) + val (key, value) = splitTag(normalized) // Then assertEquals("a", key) assertEquals("b", value) } + + @Test + fun shouldJoin() { + assertEquals("foo", joinTag("foo", null)) + assertEquals("foobar:=", joinTag("foobar:=", null)) + assertEquals("foo=bar=test", joinTag("foo=bar", "test")) + assertEquals("foobar:=:=1234.0", joinTag("foobar:=", 1234.0)) + assertEquals("foo==bar", joinTag("foo==bar", null)) + assertEquals("foo:=1235.0", joinTag("foo", 1235)) + assertEquals("foo=1235", joinTag("foo", "1235")) + assertEquals("foo:=1230.0", joinTag("foo", 1230)) + assertEquals("foo:=1234.9", joinTag("foo", 1234.9)) + assertEquals("foo:=true", joinTag("foo", true)) + assertEquals("foo=true", joinTag("foo", "true")) + } } From 98663bfb41c47b3385d439ca62494fc947d30498 Mon Sep 17 00:00:00 2001 From: Alexander Lowey-Weber Date: Mon, 7 Sep 2026 15:12:41 +0200 Subject: [PATCH 41/41] Fix error message of joinTag, fix test to expect more error messages. Signed-off-by: Alexander Lowey-Weber --- .../src/commonMain/kotlin/naksha/model/TagNormalizer.kt | 2 +- .../src/commonTest/kotlin/naksha/model/TagMapTest.kt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TagNormalizer.kt b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TagNormalizer.kt index 96cb69fa6..5c19188ee 100644 --- a/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TagNormalizer.kt +++ b/here-naksha-lib-model/src/commonMain/kotlin/naksha/model/TagNormalizer.kt @@ -164,7 +164,7 @@ class TagNormalizer private constructor() { is String -> "$key=$value" is Boolean, is Long -> "$key:=$value" is Number -> "$key:=${value.toDouble()}" - else -> throw illegalArg("Tag values can only be String, Boolean or Number, found: $value") + else -> throw illegalArg("Tag values can only be String, Boolean or Number, found: $key = $value") } private fun policyFor(tag: String): TagProcessingPolicy { diff --git a/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/TagMapTest.kt b/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/TagMapTest.kt index 3a31e9c39..674147bd3 100644 --- a/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/TagMapTest.kt +++ b/here-naksha-lib-model/src/commonTest/kotlin/naksha/model/TagMapTest.kt @@ -52,7 +52,7 @@ class TagMapTest { // Then: assertIs(failure) - assertEquals("Tag values can only be String, Boolean or Number", failure.message) + assertTrue(failure.message?.startsWith("Tag values can only be String, Boolean or Number") ?: false, "Missing message") } @Test