StringCommands.swift 19.6 KB
Newer Older
1 2
//===----------------------------------------------------------------------===//
//
3
// This source file is part of the RediStack open source project
4
//
5
// Copyright (c) 2019 RediStack project authors
6 7 8
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
9
// See CONTRIBUTORS.txt for the list of RediStack project authors
10 11 12 13 14
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//

Nathan Harris's avatar
Nathan Harris committed
15 16 17 18
import NIO

// MARK: Get

19
extension RedisClient {
Nathan Harris's avatar
Nathan Harris committed
20 21 22 23
    /// Get the value of a key.
    ///
    /// [https://redis.io/commands/get](https://redis.io/commands/get)
    /// - Parameter key: The key to fetch the value from.
Nathan Harris's avatar
Nathan Harris committed
24 25
    /// - Returns: The value stored at the key provided. If the key does not exist, the value will be `.null`.
    public func get(_ key: RedisKey) -> EventLoopFuture<RESPValue> {
26
        let args = [RESPValue(from: key)]
Nathan Harris's avatar
Nathan Harris committed
27
        return self.send(command: "GET", with: args)
28
    }
George Barnett's avatar
George Barnett committed
29

30 31 32 33 34 35
    /// Get the value of a key, converting it to the desired type.
    ///
    /// [https://redis.io/commands/get](https://redis.io/commands/get)
    /// - Parameters:
    ///     - key: The key to fetch the value from.
    ///     - type: The desired type to convert the stored data to.
Nathan Harris's avatar
Nathan Harris committed
36
    /// - Returns: The converted value stored at the key provided, otherwise `nil` if the key does not exist or fails the type conversion.
37 38
    @inlinable
    public func get<StoredType: RESPValueConvertible>(
39
        _ key: RedisKey,
40 41
        as type: StoredType.Type
    ) -> EventLoopFuture<StoredType?> {
Nathan Harris's avatar
Nathan Harris committed
42
        return self.get(key)
43
            .map { return StoredType(fromRESP: $0) }
Nathan Harris's avatar
Nathan Harris committed
44 45 46 47 48 49 50
    }

    /// Gets the values of all specified keys, using `.null` to represent non-existant values.
    ///
    /// See [https://redis.io/commands/mget](https://redis.io/commands/mget)
    /// - Parameter keys: The list of keys to fetch the values from.
    /// - Returns: The values stored at the keys provided, matching the same order.
51
    public func mget(_ keys: [RedisKey]) -> EventLoopFuture<[RESPValue]> {
Nathan Harris's avatar
Nathan Harris committed
52 53
        guard keys.count > 0 else { return self.eventLoop.makeSucceededFuture([]) }

54 55
        let args = keys.map(RESPValue.init)
        return send(command: "MGET", with: args)
56
            .tryConverting()
Nathan Harris's avatar
Nathan Harris committed
57
    }
George Barnett's avatar
George Barnett committed
58

Nathan Harris's avatar
Nathan Harris committed
59 60 61 62 63 64 65 66 67 68 69 70
    /// Gets the values of all specified keys, using `.null` to represent non-existant values.
    ///
    /// See [https://redis.io/commands/mget](https://redis.io/commands/mget)
    /// - Parameters:
    ///     - keys: The list of keys to fetch the values from.
    ///     - type: The type to convert the values to.
    /// - Returns: The values stored at the keys provided, matching the same order. Values that fail the `RESPValue` conversion will be `nil`.
    @inlinable
    public func mget<Value: RESPValueConvertible>(_ keys: [RedisKey], as type: Value.Type) -> EventLoopFuture<[Value?]> {
        return self.mget(keys)
            .map { return $0.map(Value.init(fromRESP:)) }
    }
George Barnett's avatar
George Barnett committed
71

72 73 74 75 76
    /// Gets the values of all specified keys, using `.null` to represent non-existant values.
    ///
    /// See [https://redis.io/commands/mget](https://redis.io/commands/mget)
    /// - Parameter keys: The list of keys to fetch the values from.
    /// - Returns: The values stored at the keys provided, matching the same order.
77
    public func mget(_ keys: RedisKey...) -> EventLoopFuture<[RESPValue]> {
78 79
        return self.mget(keys)
    }
George Barnett's avatar
George Barnett committed
80

Nathan Harris's avatar
Nathan Harris committed
81 82 83 84 85 86 87 88 89 90 91
    /// Gets the values of all specified keys, using `.null` to represent non-existant values.
    ///
    /// See [https://redis.io/commands/mget](https://redis.io/commands/mget)
    /// - Parameters:
    ///     - keys: The list of keys to fetch the values from.
    ///     - type: The type to convert the values to.
    /// - Returns: The values stored at the keys provided, matching the same order. Values that fail the `RESPValue` conversion will be `nil`.
    @inlinable
    public func mget<Value: RESPValueConvertible>(_ keys: RedisKey..., as type: Value.Type) -> EventLoopFuture<[Value?]> {
        return self.mget(keys, as: type)
    }
Nathan Harris's avatar
Nathan Harris committed
92 93 94 95
}

// MARK: Set

George Barnett's avatar
George Barnett committed
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
/// A condition which must hold true in order for a key to be set.
///
/// See [https://redis.io/commands/set](https://redis.io/commands/set)
public struct RedisSetCommandCondition: Hashable {
    private enum Condition: String, Hashable {
        case keyExists = "XX"
        case keyDoesNotExist = "NX"
    }

    private let condition: Condition?
    private init(_ condition: Condition?) {
        self.condition = condition
    }

    /// The `RESPValue` representation of the condition.
    @usableFromInline
    internal var commandArgument: RESPValue? {
        return self.condition.map { RESPValue(from: $0.rawValue) }
    }
}

extension RedisSetCommandCondition {
    /// No condition is required to be met in order to set the key's value.
    public static let none = RedisSetCommandCondition(.none)

    /// Only set the key if it already exists.
    ///
    /// Redis documentation refers to this as the option "XX".
    public static let keyExists = RedisSetCommandCondition(.keyExists)

    /// Only set the key if it does not already exist.
    ///
    /// Redis documentation refers to this as the option "NX".
    public static let keyDoesNotExist = RedisSetCommandCondition(.keyDoesNotExist)
}

/// The expiration to apply when setting a key.
///
/// See [https://redis.io/commands/set](https://redis.io/commands/set)
public struct RedisSetCommandExpiration: Hashable {
    private enum Expiration: Hashable {
        case keepExisting
        case seconds(Int)
        case milliseconds(Int)
    }

    private let expiration: Expiration
    private init(_ expiration: Expiration) {
        self.expiration = expiration
    }

    /// An array of `RESPValue`s representing this expiration.
    @usableFromInline
    internal func asCommandArguments() -> [RESPValue] {
        switch self.expiration {
        case .keepExisting:
            return [RESPValue(from: "KEEPTTL")]
        case .seconds(let amount):
            return [RESPValue(from: "EX"), amount.convertedToRESPValue()]
        case .milliseconds(let amount):
            return [RESPValue(from: "PX"), amount.convertedToRESPValue()]
        }
    }
}

extension RedisSetCommandExpiration {
    /// Retain the existing expiration associated with the key, if one exists.
    ///
    /// Redis documentation refers to this as "KEEPTTL".
    /// - Important: This is option is only available in Redis 6.0+. An error will be returned if this value is sent in lower versions of Redis.
    public static let keepExisting = RedisSetCommandExpiration(.keepExisting)

    /// Expire the key after the given number of seconds.
    ///
    /// Redis documentation refers to this as the option "EX".
    /// - Important: The actual amount used will be the specified value or `1`, whichever is larger.
    public static func seconds(_ amount: Int) -> RedisSetCommandExpiration {
        return RedisSetCommandExpiration(.seconds(max(amount, 1)))
    }

    /// Expire the key after the given number of milliseconds.
    ///
    /// Redis documentation refers to this as the option "PX".
    /// - Important: The actual amount used will be the specified value or `1`, whichever is larger.
    public static func milliseconds(_ amount: Int) -> RedisSetCommandExpiration {
        return RedisSetCommandExpiration(.milliseconds(max(amount, 1)))
    }
}

/// The result of a `SET` command.
public enum RedisSetCommandResult: Hashable {
    /// The command completed successfully.
    case ok

    /// The command was not performed because a condition was not met.
    ///
    /// See `RedisSetCommandCondition`.
    case conditionNotMet
}

196
extension RedisClient {
197 198 199 200 201 202 203 204 205
    /// Append a value to the end of an existing entry.
    /// - Note: If the key does not exist, it is created and set as an empty string, so `APPEND` will be similar to `SET` in this special case.
    ///
    /// See [https://redis.io/commands/append](https://redis.io/commands/append)
    /// - Parameters:
    ///     - value: The value to append onto the value stored at the key.
    ///     - key: The key to use to uniquely identify this value.
    /// - Returns: The length of the key's value after appending the additional value.
    @inlinable
206
    public func append<Value: RESPValueConvertible>(_ value: Value, to key: RedisKey) -> EventLoopFuture<Int> {
207
        let args: [RESPValue] = [
208
            .init(from: key),
209 210 211
            value.convertedToRESPValue()
        ]
        return send(command: "APPEND", with: args)
212
            .tryConverting()
213
    }
George Barnett's avatar
George Barnett committed
214

Nathan Harris's avatar
Nathan Harris committed
215 216 217 218 219 220 221 222 223 224 225 226
    /// Sets the value stored in the key provided, overwriting the previous value.
    ///
    /// Any previous expiration set on the key is discarded if the SET operation was successful.
    ///
    /// - Important: Regardless of the type of value stored at the key, it will be overwritten to a string value.
    ///
    /// [https://redis.io/commands/set](https://redis.io/commands/set)
    /// - Parameters:
    ///     - key: The key to use to uniquely identify this value.
    ///     - value: The value to set the key to.
    /// - Returns: An `EventLoopFuture` that resolves if the operation was successful.
    @inlinable
227
    public func set<Value: RESPValueConvertible>(_ key: RedisKey, to value: Value) -> EventLoopFuture<Void> {
228
        let args: [RESPValue] = [
229
            .init(from: key),
230 231 232
            value.convertedToRESPValue()
        ]
        return send(command: "SET", with: args)
Nathan Harris's avatar
Nathan Harris committed
233 234 235
            .map { _ in () }
    }

George Barnett's avatar
George Barnett committed
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
    /// Sets the key to the provided value with options to control how it is set.
    ///
    /// [https://redis.io/commands/set](https://redis.io/commands/set)
    /// - Important: Regardless of the type of data stored at the key, it will be overwritten to a "string" data type.
    ///
    ///   ie. If the key is a reference to a Sorted Set, its value will be overwritten to be a "string" data type.
    ///
    /// - Parameters:
    ///     - key: The key to use to uniquely identify this value.
    ///     - value: The value to set the key to.
    ///     - condition: The condition under which the key should be set.
    ///     - expiration: The expiration to use when setting the key. No expiration is set if `nil`.
    /// - Returns: A `NIO.EventLoopFuture` indicating the result of the operation;
    ///     `.ok` if the operation was successful and `.conditionNotMet` if the specified `condition` was not met.
    ///
    ///     If the condition `.none` was used, then the result value will always be `.ok`.
    public func set<Value: RESPValueConvertible>(
        _ key: RedisKey,
        to value: Value,
        onCondition condition: RedisSetCommandCondition,
        expiration: RedisSetCommandExpiration? = nil
    ) -> EventLoopFuture<RedisSetCommandResult> {
        var args: [RESPValue] = [
            .init(from: key),
            value.convertedToRESPValue()
        ]

        if let conditionArgument = condition.commandArgument {
            args.append(conditionArgument)
        }

        if let expiration = expiration {
            args.append(contentsOf: expiration.asCommandArguments())
        }

        return self.send(command: "SET", with: args)
            .map { return $0.isNull ? .conditionNotMet : .ok }
    }

George Barnett's avatar
George Barnett committed
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
    /// Sets the key to the provided value if the key does not exist.
    ///
    /// [https://redis.io/commands/setnx](https://redis.io/commands/setnx)
    /// - Important: Regardless of the type of data stored at the key, it will be overwritten to a "string" data type.
    ///
    /// ie. If the key is a reference to a Sorted Set, its value will be overwritten to be a "string" data type.
    /// - Parameters:
    ///     - key: The key to use to uniquely identify this value.
    ///     - value: The value to set the key to.
    /// - Returns: `true` if the operation successfully completed.
    @inlinable
    public func setnx<Value: RESPValueConvertible>(_ key: RedisKey, to value: Value) -> EventLoopFuture<Bool> {
        let args: [RESPValue] = [
            .init(from: key),
            value.convertedToRESPValue()
        ]
        return self.send(command: "SETNX", with: args)
292
            .tryConverting(to: Int.self)
George Barnett's avatar
George Barnett committed
293 294 295
            .map { $0 == 1 }
    }

George Barnett's avatar
George Barnett committed
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
    /// Sets a key to the provided value and an expiration timeout in seconds.
    ///
    /// See [https://redis.io/commands/setex](https://redis.io/commands/setex)
    /// - Important: Regardless of the type of data stored at the key, it will be overwritten to a "string" data type.
    ///
    /// ie. If the key is a reference to a Sorted Set, its value will be overwritten to be a "string" data type.
    /// - Important: The actual expiration used will be the specified value or `1`, whichever is larger.
    /// - Parameters:
    ///     - key: The key to use to uniquely identify this value.
    ///     - value: The value to set the key to.
    ///     - expiration: The number of seconds after which to expire the key.
    /// - Returns: A `NIO.EventLoopFuture` that resolves if the operation was successful.
    @inlinable
    public func setex<Value: RESPValueConvertible>(
        _ key: RedisKey,
        to value: Value,
        expirationInSeconds expiration: Int
    ) -> EventLoopFuture<Void> {
        let args: [RESPValue] = [
            .init(from: key),
            .init(from: max(1, expiration)),
            value.convertedToRESPValue()
        ]
        return self.send(command: "SETEX", with: args)
            .map { _ in () }
    }

    /// Sets a key to the provided value and an expiration timeout in milliseconds.
    ///
    /// See [https://redis.io/commands/psetex](https://redis.io/commands/psetex)
    /// - Important: Regardless of the type of data stored at the key, it will be overwritten to a "string" data type.
    ///
    /// ie. If the key is a reference to a Sorted Set, its value will be overwritten to be a "string" data type.
    /// - Important: The actual expiration used will be the specified value or `1`, whichever is larger.
    /// - Parameters:
    ///     - key: The key to use to uniquely identify this value.
    ///     - value: The value to set the key to.
    ///     - expiration: The number of milliseconds after which to expire the key.
    /// - Returns: A `NIO.EventLoopFuture` that resolves if the operation was successful.
    @inlinable
    public func psetex<Value: RESPValueConvertible>(
        _ key: RedisKey,
        to value: Value,
        expirationInMilliseconds expiration: Int
    ) -> EventLoopFuture<Void> {
        let args: [RESPValue] = [
            .init(from: key),
            .init(from: max(1, expiration)),
            value.convertedToRESPValue()
        ]
        return self.send(command: "PSETEX", with: args)
            .map { _ in () }
    }

Nathan Harris's avatar
Nathan Harris committed
350 351 352 353 354 355 356
    /// Sets each key to their respective new value, overwriting existing values.
    /// - Note: Use `msetnx(_:)` if you don't want to overwrite values.
    ///
    /// See [https://redis.io/commands/mset](https://redis.io/commands/mset)
    /// - Parameter operations: The key-value list of SET operations to execute.
    /// - Returns: An `EventLoopFuture` that resolves if the operation was successful.
    @inlinable
357
    public func mset<Value: RESPValueConvertible>(_ operations: [RedisKey: Value]) -> EventLoopFuture<Void> {
Nathan Harris's avatar
Nathan Harris committed
358 359 360 361 362 363 364 365 366 367 368
        return _mset(command: "MSET", operations)
            .map { _ in () }
    }

    /// Sets each key to their respective new value, only if all keys do not currently exist.
    /// - Note: Use `mset(_:)` if you don't care about overwriting values.
    ///
    /// See [https://redis.io/commands/msetnx](https://redis.io/commands/msetnx)
    /// - Parameter operations: The key-value list of SET operations to execute.
    /// - Returns: `true` if the operation successfully completed.
    @inlinable
369
    public func msetnx<Value: RESPValueConvertible>(_ operations: [RedisKey: Value]) -> EventLoopFuture<Bool> {
Nathan Harris's avatar
Nathan Harris committed
370
        return _mset(command: "MSETNX", operations)
371
            .tryConverting(to: Int.self)
Nathan Harris's avatar
Nathan Harris committed
372 373
            .map { return $0 == 1 }
    }
George Barnett's avatar
George Barnett committed
374

Nathan Harris's avatar
Nathan Harris committed
375
    @usableFromInline
376
    func _mset<Value: RESPValueConvertible>(
Nathan Harris's avatar
Nathan Harris committed
377
        command: String,
378
        _ operations: [RedisKey: Value]
Nathan Harris's avatar
Nathan Harris committed
379 380 381
    ) -> EventLoopFuture<RESPValue> {
        assert(operations.count > 0, "At least 1 key-value pair should be provided.")

382 383 384
        let args: [RESPValue] = operations.reduce(
            into: .init(initialCapacity: operations.count * 2),
            { (array, element) in
385
                array.append(.init(from: element.key))
386 387 388
                array.append(element.value.convertedToRESPValue())
            }
        )
Nathan Harris's avatar
Nathan Harris committed
389 390 391 392 393 394 395

        return send(command: command, with: args)
    }
}

// MARK: Increment

396
extension RedisClient {
Nathan Harris's avatar
Nathan Harris committed
397 398 399 400 401
    /// Increments the stored value by 1.
    ///
    /// See [https://redis.io/commands/incr](https://redis.io/commands/incr)
    /// - Parameter key: The key whose value should be incremented.
    /// - Returns: The new value after the operation.
402
    public func increment(_ key: RedisKey) -> EventLoopFuture<Int> {
403
        let args = [RESPValue(from: key)]
404
        return send(command: "INCR", with: args)
405
            .tryConverting()
Nathan Harris's avatar
Nathan Harris committed
406 407 408 409 410 411 412 413 414 415
    }

    /// Increments the stored value by the amount desired .
    ///
    /// See [https://redis.io/commands/incrby](https://redis.io/commands/incrby)
    /// - Parameters:
    ///     - key: The key whose value should be incremented.
    ///     - count: The amount that this value should be incremented, supporting both positive and negative values.
    /// - Returns: The new value after the operation.
    @inlinable
Nathan Harris's avatar
Nathan Harris committed
416 417 418 419
    public func increment<Value: FixedWidthInteger & RESPValueConvertible>(
        _ key: RedisKey,
        by count: Value
    ) -> EventLoopFuture<Value> {
420
        let args: [RESPValue] = [
421
            .init(from: key),
422 423 424
            .init(bulk: count)
        ]
        return send(command: "INCRBY", with: args)
425
            .tryConverting()
Nathan Harris's avatar
Nathan Harris committed
426 427 428 429 430 431 432 433 434 435
    }

    /// Increments the stored value by the amount desired.
    ///
    /// See [https://redis.io/commands/incrbyfloat](https://redis.io/commands/incrbyfloat)
    /// - Parameters:
    ///     - key: The key whose value should be incremented.
    ///     - count: The amount that this value should be incremented, supporting both positive and negative values.
    /// - Returns: The new value after the operation.
    @inlinable
Nathan Harris's avatar
Nathan Harris committed
436 437 438 439
    public func increment<Value: BinaryFloatingPoint & RESPValueConvertible>(
        _ key: RedisKey,
        by count: Value
    ) -> EventLoopFuture<Value> {
440
        let args: [RESPValue] = [
441
            .init(from: key),
442 443 444
            count.convertedToRESPValue()
        ]
        return send(command: "INCRBYFLOAT", with: args)
445
            .tryConverting()
Nathan Harris's avatar
Nathan Harris committed
446 447 448 449 450
    }
}

// MARK: Decrement

451
extension RedisClient {
Nathan Harris's avatar
Nathan Harris committed
452 453 454 455 456 457
    /// Decrements the stored value by 1.
    ///
    /// See [https://redis.io/commands/decr](https://redis.io/commands/decr)
    /// - Parameter key: The key whose value should be decremented.
    /// - Returns: The new value after the operation.
    @inlinable
458
    public func decrement(_ key: RedisKey) -> EventLoopFuture<Int> {
459
        let args = [RESPValue(from: key)]
460
        return send(command: "DECR", with: args)
461
            .tryConverting()
Nathan Harris's avatar
Nathan Harris committed
462 463 464 465 466 467 468 469 470
    }

    /// Decrements the stored valye by the amount desired.
    ///
    /// See [https://redis.io/commands/decrby](https://redis.io/commands/decrby)
    /// - Parameters:
    ///     - key: The key whose value should be decremented.
    ///     - count: The amount that this value should be decremented, supporting both positive and negative values.
    /// - Returns: The new value after the operation.
Nathan Harris's avatar
Nathan Harris committed
471 472 473 474 475
    @inlinable
    public func decrement<Value: FixedWidthInteger & RESPValueConvertible>(
        _ key: RedisKey,
        by count: Value
    ) -> EventLoopFuture<Value> {
476
        let args: [RESPValue] = [
477
            .init(from: key),
478 479 480
            .init(bulk: count)
        ]
        return send(command: "DECRBY", with: args)
481
            .tryConverting()
Nathan Harris's avatar
Nathan Harris committed
482 483
    }
}