SQLiteCpp icon indicating copy to clipboard operation
SQLiteCpp copied to clipboard

Add support for string_view

Open KingDuckZ opened this issue 5 years ago • 2 comments

Not sure if this is possible, but it would be nice to have string_view support in calls to bind()

KingDuckZ avatar Sep 04 '20 22:09 KingDuckZ

IMHO the benefits of string_view are not many for SQLiteCpp. Most strings it receives from callers are passed on to sqlite3 which requires C-style zero-terminated strings. This means for each string_view passed in, a copy of the string needs to be allocated and padded with a null-byte (since string_views will usually not be null-terminated).

Note that if the caller already has a std::string, passing string_views is actually worse than passing in the std::string by const-ref, because the c_str() member function of std::string is non-allocating in practical implementations. So with a string_view you force an extra allocation.

This means in the case of SQLiteCpp, string_views are only useful to hide the extra allocations needed in any case when passing in a substring inside a larger memory area.

pylorak avatar Mar 21 '23 01:03 pylorak

@pylorak I believe you're not quite right. SQLite3 documentation says:

If a non-negative fourth parameter is provided to sqlite3_bind_text() or sqlite3_bind_text16() or sqlite3_bind_text64() then that parameter must be the byte offset where the NUL terminator would occur assuming the string were NUL terminated. If any NUL characters occurs at byte offsets less than the value of the fourth parameter then the resulting string value will contain embedded NULs. The result of expressions involving strings with embedded NULs is undefined.

I.e. it is perfectly fine to not terminate them, and therefore using string_view would constitute an optimization, not pessimization throughout.

Furthermore, the same applies to queries. It is quite common to have fixed queries in an application. Now with C++17 literals you could do something like static const auto query = "INSERT INTO foo (bar, baz) VALUES (?, ?)"sv; to get a string_view literal which, unlike std::string is certainly not going to have heap-allocated contents and expensively initialized at start-up, yet would know its length.

ztane avatar Dec 27 '23 19:12 ztane