tobymao / sqlglot

Python SQL Parser and Transpiler
https://sqlglot.com/
MIT License
6.51k stars 671 forks source link

Retrieve originally-formatted SQL statement #3746

Closed marhar closed 3 months ago

marhar commented 3 months ago

Is your feature request related to a problem? Please describe.

I have split a file of sql statements and am executing each one.

I would like to show the user the results of each execution, using the originally formatted SQL string.

Describe the solution you'd like

The ability to retrieve start/stop indices in the original string for each parsed statement. For example, in this string

"select FoO fROM BAr; SELeCt 2+2;"

The indices would be [[0,19], [20,31]]

This would allow me to extract each statement from the source string as originally formatted.

Describe alternatives you've considered

A method that would return the originally-formatted statement directly.

Additional context

Any method is fine... the goal is to display to the user the statement as it originally appeared.

georgesittas commented 3 months ago

Providing a first-class solution for this is out of scope for now, but you can probably hack something together by manually tokenizing the SQL, chunking the tokens using TokenType.SEMICOLON as the delimiter and then calling Parser._find_sql. In order to use _find_sql, you'll have to instantiate a parser and manually call its parse method, passing the SQL and the tokens to it.

marhar commented 2 months ago

Thanks George, what you suggested works perfectly. Sqlglot is really easy to work with!

georgesittas commented 2 months ago

Glad to hear it! Thanks for following up :)