manageable-users/Sources/ManageableUsers/Utilities/Request+SQLDatabase.swift

26 lines
893 B
Swift

import Fluent
import SQLKit
extension Database {
public func withSQLConnection<T: Sendable>(user: BasicUser? = nil, _ closure: @escaping @Sendable (any SQLDatabase) async throws -> T) async throws -> T {
return try await self.withConnection { database in
guard let connection = database as? (any SQLDatabase) else {
throw NoSQLDatabaseError (database: database)
}
try await connection.raw ("""
SELECT pg_catalog.set_config ('manageable_users.active_user', \(bind: user?.fullName), FALSE)
""")
.run()
let result = try await closure (connection)
try await connection.raw ("""
SELECT pg_catalog.set_config ('manageable_users.active_user', NULL, FALSE)
""")
.run()
return result
}
}
}