marijnh / Postmodern

A Common Lisp PostgreSQL programming interface
http://marijnhaverbeke.nl/postmodern
Other
400 stars 90 forks source link

Extracting all table names from a query? #299

Closed Symbolics closed 2 years ago

Symbolics commented 2 years ago

Does anyone have any ideas on how to extract all table names from a s-sql query?

My use case involves pre-processing the tables before executing the query. I do not see any obvious way to do this, and trying to parse the s-sql expression seems like a bit of work to do in a reliable way. Alternatively I could wrap the function with a macro and have the user specify the tables, but it would be nice, since the information is already there, to extract it if possible.

Any ideas?

sabracrolleton commented 2 years ago

Do you mean including all tables from joins? Can you give an example s-sql query (anonymizing as necessary)?

Symbolics commented 2 years ago

I don't have a specific example. I'll be taking user provided s-sql queries from which I want a list of table names. There could be joins in the query.

sabracrolleton commented 2 years ago

Maybe something like this?

(defun tables-in-query (db-spec s-sql-query)
  (pomo:with-connection db-spec 
    (intersection (pomo:list-tables t)
                  (mapcar 'string
                          (s-sql::split-on-keywords ((select *) 
                                              (from * ?))
                                             s-sql-query
                                             `(,@(when from (alexandria:flatten from)))))
                  :test 'equalp)))
Symbolics commented 2 years ago

Thanks. That looks like it may work. I'd like to leave this open for a while as I go fight some fires. I'll circle back around with the solution I go with and then close.

Symbolics commented 2 years ago

Working. Thanks.