Question

I'm running into a problem where it is possible to insert a row into a table whithout specifically setting an INT NOT NULL column (defaults to 0 which is invalid for my purposes)

I create the table this way:

CREATE TABLE inventorycontrol (
     ID                         INT NOT NULL UNIQUE AUTO_INCREMENT
    ,nodeID                     INT NOT NULL CHECK (nodeID > 0)
    ,custom1                    VARCHAR(128) NOT NULL DEFAULT ''
    ,custom2                    VARCHAR(128) NOT NULL DEFAULT ''
    ,custom3                    VARCHAR(128) NOT NULL DEFAULT ''
    ,custom4                    VARCHAR(128) NOT NULL DEFAULT ''
    ,articlekey                 VARCHAR(32) NOT NULL 
    ,amount                     INT NOT NULL
    ,orderID                    INT NULL
    ,supplierID                 INT NULL
    ,customerID                 INT NULL
    ,datecreated                DATETIME NOT NULL
    ,expectedcompletion         DATETIME NOT NULL
    ,datecompleted              DATETIME NULL

    ,PRIMARY KEY (articlekey, datecreated)
)
GO

CREATE INDEX ix_InventoryArticle ON inventorycontrol ( articlekey )
GO

CREATE INDEX ix_InventoryArticle_Custom ON inventorycontrol ( nodeID, custom1, custom2, custom3, custom4 )
GO

CREATE INDEX ix_InventoryAmount ON inventorycontrol ( amount ) 
GO

CREATE INDEX ix_InventoryCreated ON inventorycontrol ( datecreated )
GO

CREATE INDEX ix_InventoryCompleted  ON inventorycontrol ( datecompleted )
GO

ALTER TABLE inventorycontrol
    ADD FOREIGN KEY fk_nodeID (nodeID) REFERENCES node(ID)
GO

I would expect this insert to fail:

INSERT INTO inventorycontrol ( articlekey, amount, datecreated, expectedcompletion, datecompleted )
VALUES
     ( 'abc', -10, '2009-01-27', '2009-01-27', NULL ) 
GO

Unfortunately, this just works. (there is no node WHERE ID=0)

Is there any way i can force this insert to fail short of creating a trigger for inserts?

Thanks in advance,

Kris

P.S. i am using mysql Ver 14.12 Distrib 5.0.45, for redhat-linux-gnu (x86_64) using readline 5.0

Was it helpful?

Solution

You need to put MySQL into strict mode

In your configuration file:

sql-mode="STRICT_ALL_TABLES"

EDIT:

You can also set it locally (and put it back) using this query:

SET @mode = @@SESSION.sql_mode;
SET sql_mode = "STRICT_ALL_TABLES";

INSERT...;

SET sql_mode = @mode;

OTHER TIPS

Set the values NOT NULL, if this dont work and you cant check the values by code before inserting the row you should put new triggers that looks for values when there is an insert or a modify call on your database.

hope this helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top