Skip to content

Instance Method

statement(_:)

Invoke the provided closure with a new SQLStatement to use for serialization.
mutating func statement(_ closure: (inout SQLStatement) -> ())

Discussion

This method is the entry point for the alternate expression serialization API provided by SQLStatement. The name of the type is somewhat misleading; the serialized result is not required to be a complete SQL “statement”; as with the usual SQLSerializer API, the inputs and resultant output can be arbitrary.

To use the “statement” API, call this method in the implentation of serialize(to:), and provide a closure which contains the serialization logic for the expression. Call methods of the SQLStatement passed to the closure to add individual textual and subexpression pieces to the final result. Do not access the SQLSerializer from inside the closure.

For example, consider SQLEnumDataType’s serialize(to:) method:

public func serialize(to serializer: inout SQLSerializer) {
    switch serializer.dialect.enumSyntax {
    case .inline:
        SQLRaw("ENUM").serialize(to: &serializer)
        SQLGroupExpression(self.cases).serialize(to: &serializer)
    default:
        SQLDataType.text.serialize(to: &serializer)
        serializer.database.logger.debug("Database does not support inline enums. Storing as TEXT instead.")
    }
}

Rewritten using statement(_:), the method becomes:

public func serialize(to serializer: inout SQLSerializer) {
    serializer.statement {
        switch $0.dialect.enumSyntax {
        case .inline:
            $0.append("ENUM", SQLGroupExpression(self.cases))
        default:
            $0.append(SQLDataType.text)
            $0.logger.debug("Database does not support inline enums. Storing as TEXT instead.")
        }
    }
}

Note

While doing so is not especially useful, this method can be called more than once within the same context; each invocation immediately serializes the statement upon return from the provided closure.