cycle / database

Database Abstraction Layer, Schema Introspection, Schema Generation, Query Builders
MIT License
54 stars 22 forks source link

💡 Subquery column alias injection #72

Open gam6itko opened 2 years ago

gam6itko commented 2 years ago

I have an idea!

I have the query with subquery columns. I need to make aliases for subquery columns for having;

$result = $database
    ->select([
        'table1.id',
        $database->select('COUNT(1)')->from('table2')->where('inner_id', new Expression('table1.id')), // as cnt1
    ])
    ->from('table1')
    ->fetchAll();

now I need to do weird things like this

$result = $database
    ->select([
        'table1.id',
        new Fragment('('.$database->select('COUNT(1)')->from('table2')->where('inner_id', new Expression('table1.id')).') as cnt1'),
    ])
    ->from('table1')
    ->having('cnt1', 1)
    ->fetchAll();

We need something like ColumnAliasInjection to make it prettier

$result = $database
    ->select([
        'table1.id',
        new ColumnAliasInjection(
            $database->select('COUNT(1)')->from('table2')->where('inner_id', new Expression('table1.id')),
            'cnt1'
        )
    ])
    ->from('table1')
    ->having('cnt1', 1)
    ->fetchAll();
AnrDaemon commented 3 months ago

Why not

->select([
        'id' => 'table1.id',
        'cnt1' => new Fragment('('.$database->select('COUNT(1)')->from('table2')->where('inner_id', new Expression('table1.id')).')'),
    ])

etc. ?

gam6itko commented 2 months ago

has common traits with #200