_real_escape(): that swaps every "%" for a placeholder * token meant for prepare(), which would silently corrupt a dump written to disk. */ final class Sql { private const SLICE = 1048576; private const ESCAPES = array( '\\' => '\\\\', "'" => "\\'", "\0" => '\\0', "\n" => '\\n', "\r" => '\\r', "\x1a" => '\\Z', ); /** * Single-quoted string literal. Raw newlines never survive, which keeps every * dumped statement on lines that do not look like statement boundaries. */ public static function quote( string $value ): string { return "'" . strtr( $value, self::ESCAPES ) . "'"; } /** * Appends quote( $value ) to $out without building the quoted copy first. * * For a 10 MB value, "'" . strtr() . "'" holds the value, the escaped copy and the joined * copy at the same moment; this holds only $out and a 1 MB slice. The escape map works on * single bytes, so cutting the value anywhere is safe. */ public static function appendQuoted( string &$out, string $value ): void { $length = strlen( $value ); $out .= "'"; if ( $length <= self::SLICE ) { $out .= strtr( $value, self::ESCAPES ); } else { for ( $at = 0; $at < $length; $at += self::SLICE ) { $out .= strtr( substr( $value, $at, self::SLICE ), self::ESCAPES ); } } $out .= "'"; } public static function ident( string $name ): string { return '`' . str_replace( '`', '``', $name ) . '`'; } /** * @param string|null $value Raw value as returned by the driver. * @param string $type Lower-case column type from SHOW COLUMNS. */ public static function literal( ?string $value, string $type ): string { if ( null === $value ) { return 'NULL'; } if ( self::isBinaryType( $type ) ) { return '' === $value ? "''" : '0x' . bin2hex( $value ); } if ( self::isNumericType( $type ) && 1 === preg_match( '/^-?\d+(\.\d+)?([eE][+-]?\d+)?$/', $value ) ) { return $value; } return self::quote( $value ); } public static function isBinaryType( string $type ): bool { return 1 === preg_match( '/^(tiny|medium|long)?blob|^(var)?binary|^bit|^geometry|^point|^linestring|^polygon|^multi|^geometrycollection/', $type ); } public static function isNumericType( string $type ): bool { return 1 === preg_match( '/^(tinyint|smallint|mediumint|int|integer|bigint|decimal|numeric|float|double|real)\b/', $type ); } public static function isIntegerType( string $type ): bool { return 1 === preg_match( '/^(tinyint|smallint|mediumint|int|integer|bigint)\b/', $type ); } public static function isTextType( string $type ): bool { return 1 === preg_match( '/^(char|varchar|tinytext|text|mediumtext|longtext)\b/', $type ); } }