如何在sqlite_orm的make_column中显式指定列类型?
Hey there! Great question—locking in specific column types like BLOB or TEXT when using sqlite_orm with class-based table declarations is totally straightforward once you know the right helper to use. Let’s break it down step by step.
The Go-To Tool: The type_() Helper Function
sqlite_orm includes a type_() function designed explicitly to override automatic type inference. All you need to do is pass the exact SQLite native type string (like "TEXT" or "BLOB") as an argument, then include it in your make_column call.
Example: Building a Table with Explicit BLOB and TEXT Columns
Let’s start with a sample data class, then adjust its columns to enforce specific types:
First, your core data structure:
#include <sqlite_orm/sqlite_orm.h> #include <string> #include <vector> struct UserProfile { int id; std::string bio; // Defaults to TEXT, but we'll explicitly define it std::vector<uint8_t> avatar; // Defaults to BLOB, let's confirm explicitly };
Now, when setting up your database storage, use type_() inside make_column to define the exact column types:
auto storage = sqlite_orm::make_storage("user_profiles.db", sqlite_orm::make_table("user_profiles", sqlite_orm::make_column("id", &UserProfile::id, sqlite_orm::primary_key()), // Explicitly set this column to TEXT sqlite_orm::make_column("bio", &UserProfile::bio, sqlite_orm::type_("TEXT")), // Explicitly set this column to BLOB sqlite_orm::make_column("avatar", &UserProfile::avatar, sqlite_orm::type_("BLOB")) ) );
Key Details to Keep in Mind:
- SQLite Type Strings: Use the official SQLite type names:
"TEXT","BLOB","INTEGER","REAL", or"NUMERIC". Case doesn’t matter (e.g.,"text"works too), but uppercase is the standard convention. - Why Explicit Typing?: Even if
sqlite_ormauto-maps your C++ type to the correct SQLite type (likestd::string→TEXT,std::vector<uint8_t>→BLOB), explicit typing helps align with existing schemas, avoid edge-case inference issues, or just document your intent clearly. - Mixing with Other Constraints: You can combine
type_()with other column modifiers likenot_null(),default_value(), orprimary_key()—just add them to themake_columnparameter list.
Bonus: Overriding Default Type Mappings
If you need a non-standard mapping (like storing an int as TEXT), this method works too:
sqlite_orm::make_column("user_id", &UserProfile::id, sqlite_orm::primary_key(), sqlite_orm::type_("TEXT"))
That’s all there is to it! This approach gives you full control over your SQLite schema while keeping the clean, class-based syntax of sqlite_orm.
内容的提问来源于stack exchange,提问作者sorosh_sabz

