MedicOneSystems / livewire-datatables

Advanced datatables using Laravel, Livewire, Tailwind CSS and Alpine JS
https://livewire-datatables.com/
MIT License
1.19k stars 258 forks source link

[SQLSRV] Export checked records fails #443

Open saulens22 opened 2 years ago

saulens22 commented 2 years ago

Using SQLSRV model and trying to export selected records to any format I get the following error:

SQLSTATE[42S22]: [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid column name 'checkbox_attribute'.

Generated query (simplified):

SELECT
    [dba].[mytable].[myunique] AS [checkbox_attribute],
    [dba].[mytable].[myunique] AS [myunique],
    [dba].[anothertable].[data] AS [data]
FROM [dba].[mytable]
LEFT JOIN [dba].[anothertable] ON [dba].[mytable].[someid] = [dba].[anothertable].[someid]
HAVING checkbox_attribute IN (_62V10CVJJ)
ORDER BY dba.mytable.myunique DESC

As I found out, SQLSRV has a bit different order of operations, so it doesn't know about checkbox_attribute alias:

  1. FROM
  2. WHERE
  3. GROUP BY
  4. HAVING <-- doesn't know about SELECT alias
  5. SELECT expressions (like x AS y)
  6. DISTINCT
  7. UNION
  8. ORDER BY
  9. TOP

Quick and dirty workaround would be to wrap query into subquery like this:

SELECT * FROM (
SELECT
    [dba].[mytable].[myunique] AS [checkbox_attribute],
    [dba].[mytable].[myunique] AS [myunique],
    [dba].[anothertable].[data] AS [data]
FROM [dba].[mytable]
LEFT JOIN [dba].[anothertable] ON [dba].[mytable].[someid] = [dba].[anothertable].[someid]
ORDER BY dba.mytable.myunique DESC
) tempdb
WHERE checkbox_attribute IN (_62V10CVJJ)

I'm not sure how to deal with it in simplified way as it would require maintaining different code for different DB engines. Anyway, I'm open to do the testing.

p08dev commented 2 years ago

When using PostgreSQL there is the same error: SQLSTATE[42703]: Undefined column: 7 ERROR: column "checkbox_attribute" does not exist

In the src/Http/Livewire/LivewireDatatables.php i fixed it with some very dirty code to make it work...

return $query->whereRaw(explode(' ', $query->columns[0])[0] . ' IN (' . implode(',', $this->selected) . ')');