22
33namespace Tempest \Database ;
44
5- use BackedEnum ;
65use Tempest \Database \Config \DatabaseDialect ;
6+ use Tempest \Mapper \SerializerFactory ;
77use Tempest \Support \Str \ImmutableString ;
8- use UnitEnum ;
98
109final class RawSql
1110{
11+ private ?RawSqlDatabaseContext $ context {
12+ get => $ this ->context ??= new RawSqlDatabaseContext ($ this ->dialect );
13+ }
14+
1215 public function __construct (
1316 private(set) DatabaseDialect $ dialect ,
1417 private(set) string $ sql ,
1518 private(set) array $ bindings ,
19+ private SerializerFactory $ serializerFactory ,
1620 ) {}
1721
1822 public function compile (): string
@@ -39,9 +43,11 @@ public function __toString(): string
3943 private function replaceNamedBindings (string $ sql , array $ bindings ): string
4044 {
4145 foreach ($ bindings as $ key => $ value ) {
42- $ placeholder = ': ' . $ key ;
43- $ formattedValue = $ this ->formatValueForSql ($ value );
44- $ sql = str_replace ($ placeholder , $ formattedValue , $ sql );
46+ $ sql = str_replace (
47+ search: ': ' . $ key ,
48+ replace: $ this ->formatValueForSql ($ value ),
49+ subject: $ sql ,
50+ );
4551 }
4652
4753 return $ sql ;
@@ -71,15 +77,14 @@ private function resolveBindingsForDisplay(): array
7177 $ bindings = [];
7278
7379 foreach ($ this ->bindings as $ key => $ value ) {
74- if (is_bool ($ value )) {
75- $ value = match ($ this ->dialect ) {
76- DatabaseDialect::POSTGRESQL => $ value ? 'true ' : 'false ' ,
77- default => $ value ? '1 ' : '0 ' ,
78- };
80+ if ($ value instanceof Query) {
81+ $ bindings [$ key ] = "( {$ value ->toRawSql ()}) " ;
82+ continue ;
7983 }
8084
81- if ($ value instanceof Query) {
82- $ value = '( ' . $ value ->toRawSql () . ') ' ;
85+ if ($ serializer = $ this ->serializerFactory ->in ($ this ->context )->forValue ($ value )) {
86+ $ bindings [$ key ] = $ serializer ->serialize ($ value );
87+ continue ;
8388 }
8489
8590 $ bindings [$ key ] = $ value ;
@@ -94,26 +99,6 @@ private function formatValueForSql(mixed $value): string
9499 return 'NULL ' ;
95100 }
96101
97- if (is_string ($ value )) {
98- if (str_starts_with ($ value , '( ' ) && str_ends_with ($ value , ') ' )) {
99- return $ value ;
100- }
101-
102- return "' " . str_replace ("' " , "'' " , $ value ) . "' " ;
103- }
104-
105- if (is_numeric ($ value )) {
106- return (string ) $ value ;
107- }
108-
109- if ($ value instanceof BackedEnum) {
110- return $ value ->value ;
111- }
112-
113- if ($ value instanceof UnitEnum) {
114- return $ value ->name ;
115- }
116-
117- return "' " . str_replace ("' " , "'' " , (string ) $ value ) . "' " ;
102+ return (string ) $ value ;
118103 }
119104}
0 commit comments