text for UTF-8 strings and ascii for ASCII-only strings. Both map to Rust’s String and &str types.
Text
Thetext type stores UTF-8 encoded strings of arbitrary length.
Using String
Using &str
For string literals and borrowed strings, you can use&str:
UTF-8 Support
Thetext type fully supports UTF-8, including emojis and international characters:
ASCII
Theascii type stores ASCII-only strings. It’s similar to text but validates that all characters are ASCII.
ASCII Validation
When deserializing anascii column, the driver validates that all bytes are valid ASCII (0-127). Non-ASCII characters will cause a deserialization error:
When to Use ASCII vs Text
- Use
textfor general-purpose strings (recommended for most cases) - Use
asciionly when you need to enforce ASCII-only data at the database level - Both types use the same Rust types (
Stringand&str)
String Serialization
BothString and &str can serialize to either text or ascii columns:
Nullable Strings
UseOption<String> or Option<&str> for nullable text columns:
String References and Lifetimes
When deserializing, you can use&str to avoid allocating a new String. This requires careful lifetime management:
Empty Strings
Empty strings are supported and are different from null:Performance Tips
-
Use
&strfor parameters: When passing string literals or temporary string slices as query parameters, use&strinstead of creating ownedStringinstances. - Avoid unnecessary cloning: When reading data, use references where possible to avoid copying strings.
-
Use
Bytesfor large text: For very large text data that you don’t need to process as a string, consider using theblobtype withBytesto avoid UTF-8 validation overhead.
Common Patterns
Case-Insensitive Comparison
String Formatting
String Truncation
See Also
- Primitive Types - Other basic data types
- Collection Types - Lists and maps of strings
- User-Defined Types - Structs containing strings
