55namespace CalebDW \SqlEntities \Grammars ;
66
77use CalebDW \SqlEntities \Contracts \SqlEntity ;
8+ use CalebDW \SqlEntities \Function_ ;
89use CalebDW \SqlEntities \View ;
910use Illuminate \Database \Connection ;
1011use Illuminate \Support \Str ;
@@ -17,10 +18,12 @@ public function __construct(
1718 ) {
1819 }
1920
21+ /** Compile the SQL statement to create the entity. */
2022 public function compileCreate (SqlEntity $ entity ): string
2123 {
2224 $ statement = match (true ) {
23- $ entity instanceof View => $ this ->compileViewCreate ($ entity ),
25+ $ entity instanceof Function_ => $ this ->compileFunctionCreate ($ entity ),
26+ $ entity instanceof View => $ this ->compileViewCreate ($ entity ),
2427
2528 default => throw new InvalidArgumentException (
2629 sprintf ('Unsupported entity [%s]. ' , $ entity ::class),
@@ -30,10 +33,12 @@ public function compileCreate(SqlEntity $entity): string
3033 return $ this ->clean ($ statement );
3134 }
3235
36+ /** Compile the SQL statement to drop the entity. */
3337 public function compileDrop (SqlEntity $ entity ): string
3438 {
3539 $ statement = match (true ) {
36- $ entity instanceof View => $ this ->compileViewDrop ($ entity ),
40+ $ entity instanceof Function_ => $ this ->compileFunctionDrop ($ entity ),
41+ $ entity instanceof View => $ this ->compileViewDrop ($ entity ),
3742
3843 default => throw new InvalidArgumentException (
3944 sprintf ('Unsupported entity [%s]. ' , $ entity ::class),
@@ -47,10 +52,21 @@ public function compileDrop(SqlEntity $entity): string
4752 public function supportsEntity (SqlEntity $ entity ): bool
4853 {
4954 return match (true ) {
50- $ entity instanceof View => true ,
51- default => false ,
55+ $ entity instanceof Function_ => true ,
56+ $ entity instanceof View => true ,
57+ default => false ,
5258 };
5359 }
60+
61+ abstract protected function compileFunctionCreate (Function_ $ entity ): string ;
62+
63+ protected function compileFunctionDrop (Function_ $ entity ): string
64+ {
65+ return <<<SQL
66+ DROP FUNCTION IF EXISTS {$ entity ->name ()}
67+ SQL ;
68+ }
69+
5470 abstract protected function compileViewCreate (View $ entity ): string ;
5571
5672 protected function compileViewDrop (View $ entity ): string
@@ -88,7 +104,12 @@ protected function compileCheckOption(string|true|null $option): string
88104 protected function clean (string $ value ): string
89105 {
90106 return Str::of ($ value )
91- ->replaceMatches ('/ +/ ' , ' ' )
107+ // remove extra spaces in between words
108+ ->replaceMatches ('/(?<=\S) {2,}(?=\S)/ ' , ' ' )
109+ // remove trailing spaces at end of line
110+ ->replaceMatches ('/ +\n/ ' , "\n" )
111+ // remove duplicate new lines
112+ ->replaceMatches ('/\n{2,}/ ' , "\n" )
92113 ->trim ()
93114 ->value ();
94115 }
0 commit comments