@@ -127,25 +127,37 @@ defmodule Ecto.Adapters.Postgres do
127127
128128 @ impl true
129129 def storage_up ( opts ) do
130- database = Keyword . fetch! ( opts , :database ) || raise ":database is nil in repository configuration"
130+ database =
131+ Keyword . fetch! ( opts , :database ) || raise ":database is nil in repository configuration"
132+
131133 encoding = if opts [ :encoding ] == :unspecified , do: nil , else: opts [ :encoding ] || "UTF8"
132134 maintenance_database = Keyword . get ( opts , :maintenance_database , @ default_maintenance_database )
133135 opts = Keyword . put ( opts , :database , maintenance_database )
134136
135- command =
136- ~s( CREATE DATABASE "#{ database } ")
137- |> concat_if ( encoding , & "ENCODING '#{ & 1 } '" )
138- |> concat_if ( opts [ :template ] , & "TEMPLATE=#{ & 1 } " )
139- |> concat_if ( opts [ :lc_ctype ] , & "LC_CTYPE='#{ & 1 } '" )
140- |> concat_if ( opts [ :lc_collate ] , & "LC_COLLATE='#{ & 1 } '" )
137+ check_existence_command = "SELECT FROM pg_database WHERE datname = '#{ database } '"
141138
142- case run_query ( command , opts ) do
143- { :ok , _ } ->
144- :ok
145- { :error , % { postgres: % { code: :duplicate_database } } } ->
139+ case run_query ( check_existence_command , opts ) do
140+ { :ok , % { num_rows: 1 } } ->
146141 { :error , :already_up }
147- { :error , error } ->
148- { :error , Exception . message ( error ) }
142+
143+ _ ->
144+ create_command =
145+ ~s( CREATE DATABASE "#{ database } ")
146+ |> concat_if ( encoding , & "ENCODING '#{ & 1 } '" )
147+ |> concat_if ( opts [ :template ] , & "TEMPLATE=#{ & 1 } " )
148+ |> concat_if ( opts [ :lc_ctype ] , & "LC_CTYPE='#{ & 1 } '" )
149+ |> concat_if ( opts [ :lc_collate ] , & "LC_COLLATE='#{ & 1 } '" )
150+
151+ case run_query ( create_command , opts ) do
152+ { :ok , _ } ->
153+ :ok
154+
155+ { :error , % { postgres: % { code: :duplicate_database } } } ->
156+ { :error , :already_up }
157+
158+ { :error , error } ->
159+ { :error , Exception . message ( error ) }
160+ end
149161 end
150162 end
151163
0 commit comments