fnc12 / sqlite_orm

❤️ SQLite ORM light header only library for modern C++
GNU Affero General Public License v3.0
2.19k stars 305 forks source link

How to select a NULL value for a column in a select? #1306

Closed juandent closed 2 weeks ago

juandent commented 2 weeks ago

Hi, I want to represent this SQL in sqlite_orm:

SELECT A.*, B.*
FROM A, B 
WHERE condition
UNION ALL
SELECT A.*, NULL, NULL, …, NULL 
FROM A 
WHERE A.pkey NOT IN(SELECT A.pkey FROM A, B WHERE condition)

Here is my attempt but it does not compile:

    auto ex = select(union_all(select(columns(asterisk<Employee>(), &EmploymentHistory::id, &EmploymentHistory::fk_employee), from<Employee>(), inner_join<EmploymentHistory>(on(c(&EmploymentHistory::fk_employee) == &Employee::id))),
        select(columns(asterisk<Employee>(), nullptr, nullptr), from<Employee>(), where(not_in(&Employee::id, select(&Employee::id))))));
    auto sqll = storage.dump(ex);
    auto prep = storage.prepare(ex);
    auto rrr = storage.execute(prep);
fnc12 commented 2 weeks ago

@juandent what compilation error do you get?

juandent commented 2 weeks ago

Errors like this:

error C2338: static_assert failed: 'Compound select statements must return a common type'
error C2672: 'sqlite_orm::internal::row_value_extractor': no matching overloaded function **found**
sqlite_orm.h(22521,27): error C3553: decltype expects an expression not a type
orm.h(22522,22): error C2976: 'std::vector': too few template arguments

etc,etc

juandent commented 2 weeks ago

Klaus thanks!!

juandent commented 2 weeks ago

Solution: use null_int instead of nullptr

constexpr std::optional<int> null_int;

auto rows = storage.select(union_all(select(columns(asterisk<Employee>(), &EmploymentHistory::id, &EmploymentHistory::fk_employee), from<Employee>(), inner_join<EmploymentHistory>(on(c(&EmploymentHistory::fk_employee) == &Employee::id))),
        select(columns(asterisk<Employee>(), null_int, null_int), from<Employee>(), where(not_in(&Employee::id, select(&EmploymentHistory::fk_employee))))));