]> git.openstreetmap.org Git - rails.git/blobdiff - vendor/gems/composite_primary_keys-1.1.0/lib/composite_primary_keys/connection_adapters/postgresql_adapter.rb
Freezing composite primary key so that we can apply TomH's patch to it, and that...
[rails.git] / vendor / gems / composite_primary_keys-1.1.0 / lib / composite_primary_keys / connection_adapters / postgresql_adapter.rb
diff --git a/vendor/gems/composite_primary_keys-1.1.0/lib/composite_primary_keys/connection_adapters/postgresql_adapter.rb b/vendor/gems/composite_primary_keys-1.1.0/lib/composite_primary_keys/connection_adapters/postgresql_adapter.rb
new file mode 100644 (file)
index 0000000..65fce48
--- /dev/null
@@ -0,0 +1,53 @@
+module ActiveRecord
+  module ConnectionAdapters
+    class PostgreSQLAdapter < AbstractAdapter
+      
+      # This mightn't be in Core, but count(distinct x,y) doesn't work for me
+      def supports_count_distinct? #:nodoc:
+        false
+      end
+
+      def concat(*columns)
+        columns = columns.map { |c| "CAST(#{c} AS varchar)" }
+        "(#{columns.join('||')})"
+      end
+      
+      # Executes an INSERT query and returns the new record's ID
+      def insert(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil)
+        # Extract the table from the insert sql. Yuck.
+        table = sql.split(" ", 4)[2].gsub('"', '')
+
+        # Try an insert with 'returning id' if available (PG >= 8.2)
+        if supports_insert_with_returning?
+          pk, sequence_name = *pk_and_sequence_for(table) unless pk
+          if pk
+            quoted_pk = if pk.is_a?(Array)
+                          pk.map { |col| quote_column_name(col) }.join(ID_SEP)
+                        else
+                          quote_column_name(pk)
+                        end
+            id = select_value("#{sql} RETURNING #{quoted_pk}")
+            clear_query_cache
+            return id
+          end
+        end
+
+        # Otherwise, insert then grab last_insert_id.
+        if insert_id = super
+          insert_id
+        else
+          # If neither pk nor sequence name is given, look them up.
+          unless pk || sequence_name
+            pk, sequence_name = *pk_and_sequence_for(table)
+          end
+
+          # If a pk is given, fallback to default sequence name.
+          # Don't fetch last insert id for a table without a pk.
+          if pk && sequence_name ||= default_sequence_name(table, pk)
+            last_insert_id(table, sequence_name)
+          end
+        end
+      end
+    end
+  end
+end