Permalink
Browse files

Explicitly mark primary keys as NOT NULL on SQLite

SQLite, in violation of the SQL standard, does not consider
primary keys as being NOT NULL.  For integer primary keys,
it automatically makes them autoincrementing, so if you
attempt to insert NULL, it just ignores you and uses the
next autoincrementing integer.  For non-Integer primary
keys, it will happily allow NULL values.  This explicitly
marks primary key columns as NOT NULL, so SQLite behaves
more like other SQL databases.
  • Loading branch information...
1 parent 44b3e6b commit 30c8bc7088613803312403052587b8b142147dee @jeremyevans committed Oct 25, 2012
Showing with 13 additions and 0 deletions.
  1. +2 −0 CHANGELOG
  2. +6 −0 lib/sequel/adapters/shared/sqlite.rb
  3. +5 −0 spec/integration/schema_test.rb
View
@@ -1,5 +1,7 @@
=== HEAD
+* Explicitly mark primary keys as NOT NULL on SQLite (jeremyevans)
+
* Add support for renaming primary key columns on MySQL (jeremyevans)
* Add connection_validator extension for automatically checking connections and transparently handling disconnects (jeremyevans)
@@ -284,6 +284,12 @@ def column_definition_default_sql(sql, column)
sql << " DEFAULT (#{literal(column[:default])})" if column.include?(:default)
end
+ # Add null/not null SQL fragment to column creation SQL.
+ def column_definition_null_sql(sql, column)
+ column = column.merge(:null=>false) if column[:primary_key]
+ super(sql, column)
+ end
+
# Array of PRAGMA SQL statements based on the Database options that should be applied to
# new connections.
def connection_pragmas
@@ -389,6 +389,11 @@
@ds.all.should == [{:id=>i, :item_id=>nil}]
end
+ specify "should not allow NULLs in a primary key" do
+ @db.create_table!(:items){String :id, :primary_key=>true}
+ proc{@ds.insert(:id=>nil)}.should raise_error(Sequel::DatabaseError)
+ end
+
specify "should rename columns correctly" do
@db.create_table!(:items){Integer :id}
@ds.insert(:id=>10)

0 comments on commit 30c8bc7

Please sign in to comment.