简体   繁体   中英

How to get DataMapper to not specify a NULL default value

I'm getting an error when I use DataMapper's auto_upgrade! method to add fields in an SQLite3 db based on the properties defined in my code:

DataObjects::SyntaxError at /history
Cannot add a NOT NULL column with default value NULL

An example of an offending line would be:

property :fieldname, Text,  required: true

The error goes away if I (a) remove the line, (b) remove required: true , (c) change true to false , or (d) add a default value.

SQLite does not require a default value to be specified for every field, so this problem is definitely with DataMapper, not SQLite.

How can I get around this, so DataMapper can specify that a field is required without assuming that not specifying a default value automatically means the default should be NULL?

(If you want to know more about why I'm designing this way: there will be another client process accessing SQLite and logging data into the SQLite database, while a Sinatra app will be pulling data out of the db for display in a browser. I want the database therefore to enforce the field requirements, but DM's auto_upgrade is a very convenient way to be able to upgrade the database as needed—so long as it doesn't foul things up in the process.)

You are requiring the field, hence it cannot be NULL. This is simple table properties.

When DataMapper runs auto_upgrade! it runs the SQL commands on the database.

CREATE TABLE Test
(
  P_Id int NOT NULL,
  lname varchar(255) NOT NULL,
  fname varchar(255),
  Address varchar(255),
  City varchar(255)
)

And doing something like this won't work.

CREATE TABLE Test
(
  P_Id int NOT NULL,
  lname varchar(255) NOT NULL DEFAULT NULL,
  fname varchar(255),
  Address varchar(255),
  City varchar(255)
)

I tested it in MySQL and this is the error.

02:52:43 CREATE TABLE TestTest ( P_Id int NOT NULL, lname varchar(255) NOT NULL DEFAULT NULL, fname varchar(255), Address varchar(255), City varchar(255) ) Error Code: 1067. Invalid default value for 'lname' 0.062 sec

Correction: SQLite does allow you to create a table with such properties. However, when trying to insert anything to that table makes it throw an error whether the field is NULL or not. So DataMapper might be doing some sanitation for your before even creating the table.

It is not clear to me if you are creating a new table or modifying an existing one.

If you have an existing table and are trying to alter it with a column defined as NOT NULL, then you must provide a default value so that the existing rows can be migrated. The RDBMS needs to know what to put in the field for pre-existing rows.

If you are creating a new table, then the property definition you have should be fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM