Skip to content

SQL Compression

Vitaly Tomilov edited this page Nov 27, 2019 · 11 revisions

In addition to minification, this library can compress SQL, by removing all unnecessary white spaces.

However, while the default minification is always a safe operation, compression may not always be, when applied to pseudo-SQL.

Pseudo SQL is what contains dynamic variables inside, which depending on the syntax, may result in compression removing spaces around variables, which in turn may invalidate the SQL after the variable values are injected.

Example:

SELECT * FROM table WHERE col = $(prop) ORDER BY col

After compression it will be:

SELECT*FROM table WHERE col=$(prop)ORDER BY col

And if variable $(prop) represents a number, it will be fused with the ORDER clause, producing an invalid SQL.

This happens because in regular SQL symbol ) never needs a space after it, so it is removed.

Variables syntax compatible with compression

The following variable syntax inside SQL is always safe to be used with SQL compression:

  • $1, $2, ...
  • ${prop1}, ${prop2},...

Variables syntax incompatible with compression

The following variable syntax may result in breaking dynamic SQL after compression:

  • $(prop)
  • $[prop]
  • $<prop>
  • $/prop/

because symbols ), ], > and / do not need a space after them within the regular SQL syntax.

Conclusion

When writing external SQL files, best is to always use variables syntax that won't create problems related to SQL compression, i.e. either $1, $2,... or ${prop1}, ${prop2},... syntax.