Transpiling
transpile() parses SQL in one dialect and generates it in another. It is the core of the package.
Signature
use Kwasii\LaravelSqlParser\Facades\LaravelSqlParser as Sql;
/**
* @param bool|array<string, mixed> $options generator options, or just the pretty flag
* @return list<string>
*/
Sql::transpile(string $sql, string|Dialect|null $from = null, string|Dialect|null $to = null, bool|array $options = []);
It returns one string per statement. Multiple statements are split on ; and each is transpiled independently.
Sql::transpile('SELECT 1; SELECT 2', 'mysql', 'postgres');
// ['SELECT 1', 'SELECT 2']
Dialect defaults
- When
from is omitted, the configured default_dialect is used, falling back to the driver of your default database connection.
- When
to is omitted, SQL is written back in the same dialect (useful for normalization and pretty-printing).
- Laravel driver names work everywhere:
mysql, mariadb, pgsql, sqlite, sqlsrv, plus aliases like postgres, tsql, mssql.
Sql::transpile('SELECT IFNULL(a, 1) FROM t LIMIT 5', from: 'mysql', to: 'tsql');
// ['SELECT TOP 5 COALESCE(a, 1) FROM t']
Pretty printing
Pass true or ['pretty' => true] as the fourth argument:
Sql::transpile('SELECT a, b FROM t', 'mysql', 'postgres', true);
// ["SELECT\n a,\n b\nFROM t"]
You can also set pretty => true in config to apply it globally.
What gets rewritten
- Functions (
IFNULL to COALESCE, dialect-specific date and string functions)
- Limits and pagination (
LIMIT to TOP, FETCH FIRST, placeholder styles)
- Quoting (
"col", `col`, [col] per dialect)
- Operators (
ILIKE to LOWER(a) LIKE LOWER(?) where unsupported)
- Types, casts, and literals per target dialect
Transpiling with bindings
Plain transpile() handles SQL text. If you have ? placeholders plus a bindings array, use transpileQuery() — some rewrites move or duplicate placeholders:
$result = Sql::transpileQuery(
'SELECT * FROM users WHERE age > ? LIMIT ?',
[18, 10],
from: 'mysql',
to: 'sqlsrv'
);
// ['sql' => 'SELECT TOP (?) * FROM [users] WHERE [age] > ?', 'bindings' => [10, 18]]
See Query builder macros for the full explanation.
Without Laravel
use Kwasii\LaravelSqlParser\Dialects\Dialect;
Dialect::transpile('SELECT IFNULL(a, 1)', read: 'mysql', write: 'postgres');
See Without Laravel.
Caching transpiles
Repeated transpiles can be memoized per-process and cached in Laravel's cache store. Enable in config — ideal for Octane and queue workers. See Performance.