Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for pragma tables #553

Open
fmattern opened this issue Jan 11, 2024 · 1 comment
Open

Support for pragma tables #553

fmattern opened this issue Jan 11, 2024 · 1 comment

Comments

@fmattern
Copy link

Using sqlite a statement like
select name from pragma_table_info('mytable')
is supported to get the column names of a database table.

With sqlpp11 I like to use it as a normal table, generating the struct for the columns and for the table like this:

struct TableInfo
	: sqlpp::table_t<TableInfo, TableInfo_::Cid, TableInfo_::Name, TableInfo_::Type, TableInfo_::Notnull, TableInfo_::DfltValue, TableInfo_::Pk> {
	struct _alias_t {
		static constexpr const char _literal[] = "pragma_table_info('mytable')";
		using _name_t = sqlpp::make_char_sequence<sizeof(_literal), _literal>;
		template <typename T>
		struct _member_t {
			T tableinfo;
			T& operator()() { return tableinfo; }
			const T& operator()() const { return tableinfo; }
		};
	};
};

and getting this information as a normal table:

for (const auto& col: db(select(tableInfo.name).from(tableInfo).unconditionally())) {
	std::cout << col.name << std::endl;
}

This almost works, the problem is that in column.h the serialization always generate a "table.column" which does not work in this case.
A quick fix to improve it would be the following:

 template <typename Context, typename Table, typename ColumnSpec>
 Context& serialize(const column_t<Table, ColumnSpec>&, Context& context)
 {
   using T = column_t<Table, ColumnSpec>;
   std::string table = name_of<typename T::_table>::template char_ptr<Context>();
   if (!table.starts_with("pragma_")) {
       context << table << '.';
   }
   context << name_of<T>::template char_ptr<Context>();
   return context;
 }

Do you have a better idea to use the pragma_table_info in sqlpp11 or is it possible to exclude the table prefix on pragma tables like this fix?

@rbock
Copy link
Owner

rbock commented Jan 12, 2024

Thanks for reaching out and the initial idea.

Given that the table name is known, we should be able to do something like this:

constexpr bool is_pragma_table = ....
if (!is_pragma_table) ...

That would avoid creating a temporary string and a runtime branch.

WDYT?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants