@@ -3,6 +3,8 @@ import Foundation
33
44/// A type that can encode itself to a postgres wire binary representation.
55public protocol PostgresEncodable {
6+ // TODO: Rename to `PostgresThrowingEncodable` with next major release
7+
68 /// identifies the data type that we will encode into `byteBuffer` in `encode`
79 static var psqlType : PostgresDataType { get }
810
@@ -14,6 +16,16 @@ public protocol PostgresEncodable {
1416 func encode< JSONEncoder: PostgresJSONEncoder > ( into byteBuffer: inout ByteBuffer , context: PostgresEncodingContext < JSONEncoder > ) throws
1517}
1618
19+ /// A type that can encode itself to a postgres wire binary representation. It enforces that the
20+ /// ``PostgresEncodable/encode(into:context:)`` does not throw. This allows users
21+ /// to create ``PostgresQuery``s using the `ExpressibleByStringInterpolation` without
22+ /// having to spell `try`.
23+ public protocol PostgresNonThrowingEncodable : PostgresEncodable {
24+ // TODO: Rename to `PostgresEncodable` with next major release
25+
26+ func encode< JSONEncoder: PostgresJSONEncoder > ( into byteBuffer: inout ByteBuffer , context: PostgresEncodingContext < JSONEncoder > )
27+ }
28+
1729/// A type that can decode itself from a postgres wire binary representation.
1830///
1931/// If you want to conform a type to PostgresDecodable you must implement the decode method.
@@ -90,6 +102,26 @@ extension PostgresEncodable {
90102 }
91103}
92104
105+ extension PostgresNonThrowingEncodable {
106+ @inlinable
107+ func encodeRaw< JSONEncoder: PostgresJSONEncoder > (
108+ into buffer: inout ByteBuffer ,
109+ context: PostgresEncodingContext < JSONEncoder >
110+ ) {
111+ // The length of the parameter value, in bytes (this count does not include
112+ // itself). Can be zero.
113+ let lengthIndex = buffer. writerIndex
114+ buffer. writeInteger ( 0 , as: Int32 . self)
115+ let startIndex = buffer. writerIndex
116+ // The value of the parameter, in the format indicated by the associated format
117+ // code. n is the above length.
118+ self . encode ( into: & buffer, context: context)
119+
120+ // overwrite the empty length, with the real value
121+ buffer. setInteger ( numericCast ( buffer. writerIndex - startIndex) , at: lengthIndex, as: Int32 . self)
122+ }
123+ }
124+
93125/// A context that is passed to Swift objects that are encoded into the Postgres wire format. Used
94126/// to pass further information to the encoding method.
95127public struct PostgresEncodingContext < JSONEncoder: PostgresJSONEncoder > {
0 commit comments