Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ public struct CreateCommand: MistDemoCommand, OutputFormatting {
}

/// Generate a unique record name
private func generateRecordName() -> String {
internal func generateRecordName() -> String {
let timestamp = Int(Date().timeIntervalSince1970)
let minSuffix = MistDemoConstants.Limits.randomSuffixMin
let maxSuffix = MistDemoConstants.Limits.randomSuffixMax
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
//
// QueryCommand+FilterParsing.swift
// MistDemo
//
// Created by Leo Dion.
// Copyright © 2026 BrightDigit.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
//

import Foundation
import MistKit

extension QueryCommand {
/// Parse a single filter expression "field:operator:value" into a QueryFilter
@available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *)
internal static func parseFilter(_ filterString: String) throws -> QueryFilter {
let components = filterString.split(
separator: ":", maxSplits: 2, omittingEmptySubsequences: false
)

guard components.count == 3 else {
throw QueryError.invalidFilter(filterString, expected: "field:operator:value")
}

let field = String(components[0]).trimmingCharacters(in: .whitespaces)
let operatorString = String(components[1]).trimmingCharacters(in: .whitespaces)
let value = String(components[2])

guard !field.isEmpty else {
throw QueryError.emptyFieldName(filterString)
}

return try buildFilter(field: field, operatorString: operatorString, value: value)
}

/// Build a QueryFilter from parsed components.
@available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *)
internal static func buildFilter(
field: String,
operatorString: String,
value: String
) throws -> QueryFilter {
if let comparison = buildComparisonFilter(
field: field, operatorString: operatorString, value: value
) {
return comparison
}
return try buildSpecialFilter(
field: field, operatorString: operatorString, value: value
)
}

/// Build comparison-based filters (equals, not equals, greater/less than).
@available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *)
// swiftlint:disable:next cyclomatic_complexity
internal static func buildComparisonFilter(
field: String,
operatorString: String,
value: String
) -> QueryFilter? {
switch operatorString.lowercased() {
case "eq", "equals", "==", "=":
return .equals(field, inferFieldValue(value))
case "ne", "not_equals", "!=":
return .notEquals(field, inferFieldValue(value))
case "gt", ">":
return .greaterThan(field, inferFieldValue(value))
case "gte", ">=":
return .greaterThanOrEquals(
field, inferFieldValue(value)
)
case "lt", "<":
return .lessThan(field, inferFieldValue(value))
case "lte", "<=":
return .lessThanOrEquals(
field, inferFieldValue(value)
)
default:
return nil
}
}

/// Build string and list-based filters.
@available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *)
internal static func buildSpecialFilter(
field: String,
operatorString: String,
value: String
) throws -> QueryFilter {
switch operatorString.lowercased() {
case "contains", "like":
return .containsAllTokens(field, value)
case "begins_with", "starts_with":
return .beginsWith(field, value)
case "in":
let values = value.split(separator: ",").map {
inferFieldValue(String($0))
}
return .in(field, values)
case "not_in":
let values = value.split(separator: ",").map {
inferFieldValue(String($0))
}
return .notIn(field, values)
default:
throw QueryError.unsupportedOperator(operatorString)
}
}

/// Infer a FieldValue from a string.
internal static func inferFieldValue(
_ string: String
) -> FieldValue {
if let intValue = Int64(string) {
return .int64(Int(intValue))
}
if let doubleValue = Double(string) {
return .double(doubleValue)
}
return .string(string)
}

/// Check if a field should be included based on field filter
internal static func shouldIncludeField(_ fieldName: String, fields: [String]?) -> Bool {
guard let fields = fields, !fields.isEmpty else {
return true // Include all fields if no filter specified
}

return fields.contains { requestedField in
fieldName.lowercased() == requestedField.lowercased()
}
}
}
122 changes: 1 addition & 121 deletions Examples/MistDemo/Sources/MistDemoKit/Commands/QueryCommand.swift
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ public struct QueryCommand: MistDemoCommand, OutputFormatting {
let filters: [QueryFilter]? =
config.filters.isEmpty
? nil
: try config.filters.map { try parseFilter($0) }
: try config.filters.map { try Self.parseFilter($0) }
recordInfos = try await client.queryRecords(
recordType: config.recordType,
filters: filters,
Expand All @@ -98,126 +98,6 @@ public struct QueryCommand: MistDemoCommand, OutputFormatting {
throw QueryError.operationFailed(error.localizedDescription)
}
}

/// Parse a single filter expression "field:operator:value" into a QueryFilter
@available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *)
private func parseFilter(_ filterString: String) throws -> QueryFilter {
let components = filterString.split(
separator: ":", maxSplits: 2, omittingEmptySubsequences: false
)

guard components.count == 3 else {
throw QueryError.invalidFilter(filterString, expected: "field:operator:value")
}

let field = String(components[0]).trimmingCharacters(in: .whitespaces)
let operatorString = String(components[1]).trimmingCharacters(in: .whitespaces)
let value = String(components[2])

guard !field.isEmpty else {
throw QueryError.emptyFieldName(filterString)
}

return try buildFilter(field: field, operatorString: operatorString, value: value)
}

/// Build a QueryFilter from parsed components.
@available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *)
private func buildFilter(
field: String,
operatorString: String,
value: String
) throws -> QueryFilter {
if let comparison = buildComparisonFilter(
field: field, operatorString: operatorString, value: value
) {
return comparison
}
return try buildSpecialFilter(
field: field, operatorString: operatorString, value: value
)
}

// Build comparison-based filters (equals, not equals, greater/less than).
@available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *)
// swiftlint:disable:next cyclomatic_complexity
private func buildComparisonFilter(
field: String,
operatorString: String,
value: String
) -> QueryFilter? {
switch operatorString.lowercased() {
case "eq", "equals", "==", "=":
return .equals(field, inferFieldValue(value))
case "ne", "not_equals", "!=":
return .notEquals(field, inferFieldValue(value))
case "gt", ">":
return .greaterThan(field, inferFieldValue(value))
case "gte", ">=":
return .greaterThanOrEquals(
field, inferFieldValue(value)
)
case "lt", "<":
return .lessThan(field, inferFieldValue(value))
case "lte", "<=":
return .lessThanOrEquals(
field, inferFieldValue(value)
)
default:
return nil
}
}

/// Build string and list-based filters.
@available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *)
private func buildSpecialFilter(
field: String,
operatorString: String,
value: String
) throws -> QueryFilter {
switch operatorString.lowercased() {
case "contains", "like":
return .containsAllTokens(field, value)
case "begins_with", "starts_with":
return .beginsWith(field, value)
case "in":
let values = value.split(separator: ",").map {
inferFieldValue(String($0))
}
return .in(field, values)
case "not_in":
let values = value.split(separator: ",").map {
inferFieldValue(String($0))
}
return .notIn(field, values)
default:
throw QueryError.unsupportedOperator(operatorString)
}
}

/// Infer a FieldValue from a string.
private func inferFieldValue(
_ string: String
) -> FieldValue {
if let intValue = Int64(string) {
return .int64(Int(intValue))
}
if let doubleValue = Double(string) {
return .double(doubleValue)
}
return .string(string)
}

/// Check if a field should be included based on field filter
private func shouldIncludeField(_ fieldName: String, fields: [String]?) -> Bool {
guard let fields = fields, !fields.isEmpty else {
return true // Include all fields if no filter specified
}

return fields.contains { requestedField in
fieldName.lowercased() == requestedField.lowercased()
}
}
}

// QueryError is now defined in Errors/QueryError.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
//
// CreateCommandTests+GenerateRecordName.swift
// MistDemoTests
//
// Created by Leo Dion.
// Copyright © 2026 BrightDigit.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
//

import Foundation
import Testing

@testable import MistDemoKit

extension CreateCommandTests {
@Suite("generateRecordName helper")
internal struct GenerateRecordNameHelper {
@Test("generateRecordName prefixes with lowercased record type")
internal func lowercasePrefix() async throws {
let baseConfig = try await MistDemoConfig()
let config = CreateConfig(base: baseConfig, recordType: "Article")
let command = CreateCommand(config: config)

let name = command.generateRecordName()

#expect(name.hasPrefix("article-"))
}

@Test("generateRecordName format is <type>-<timestamp>-<4-digit suffix>")
internal func threePartFormat() async throws {
let baseConfig = try await MistDemoConfig()
let config = CreateConfig(base: baseConfig, recordType: "Note")
let command = CreateCommand(config: config)

let name = command.generateRecordName()
let parts = name.split(separator: "-").map(String.init)

#expect(parts.count == 3)
#expect(parts[0] == "note")
#expect(Int(parts[1]) != nil, "expected a unix timestamp; got \(parts[1])")
let suffix = try #require(Int(parts[2]))
#expect(suffix >= MistDemoConstants.Limits.randomSuffixMin)
#expect(suffix <= MistDemoConstants.Limits.randomSuffixMax)
}

@Test("generateRecordName produces distinct values across many calls")
internal func distinctness() async throws {
let baseConfig = try await MistDemoConfig()
let config = CreateConfig(base: baseConfig, recordType: "Note")
let command = CreateCommand(config: config)

// The random suffix has ~9000 values; 200 samples should be highly unique.
// Allow some collisions but require that most samples are distinct, which
// verifies the random component is being used.
let names = (0..<200).map { _ in command.generateRecordName() }
let unique = Set(names)
#expect(unique.count > 150)
}
}
}
Loading
Loading