Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change default value of allowNull for all models #504

Closed
ShimShamSam opened this issue Mar 30, 2013 · 13 comments
Closed

Change default value of allowNull for all models #504

ShimShamSam opened this issue Mar 30, 2013 · 13 comments
Labels

Comments

@ShimShamSam
Copy link

I try to avoid null values as much as possible, unfortunately I have to go through every model and add "allowNull: false" to every column definition. It would be nice if there was some connection-wide setting that allowed me to default allowNull to false.

@janmeier
Copy link
Member

Pass omitNull: true to the options when you instantiate the sequelize object. eg:

var sequelize = new Sequelize("db", "user", "pass", {
    omitNull: true
});

@ShimShamSam
Copy link
Author

That's close, but it would be nice if it adds NOT NULL to the schema when I do a sync.

@janmeier
Copy link
Member

janmeier commented Jun 6, 2013

Sorry for leaving you hanging - in that case you want to use allowNull: false

The docs on the homepage are not very clear on the subject right now, but if you look at the latest version on GH it should make more sense

https://github.com/sequelize/sequelize-doc/blob/master/views/documentation/sections/models/definition.md

@janmeier
Copy link
Member

janmeier commented Jun 6, 2013

The difference being that omitNull: false does not send null values to the DB, and that allowNull: false adds NOT NULL to the schema

@durango durango closed this as completed Jul 31, 2013
@benkaiser
Copy link

I'd like to reopen this issue. It appears that the answer of using allowNull, simply refers to the attribute level of a model, and not globally as this question from @ShimShamSam was referring.

There is no global allowNull attribute (allowNull always default to true if omitted).

@janmeier @durango could this issue be re-opened?

@mickhansen
Copy link
Contributor

@benkaiser What are you looking to achieve? A default allowNull: false for all attributes? You could simply implement a beforeDefine hook and modify attributes.

@benkaiser
Copy link

@mickhansen does that still have to be added at a model level? Or can you add a hook for all of sequelize in one place?

@mickhansen
Copy link
Contributor

@benkaiser A beforeDefine hook is added on the sequelize instance and called each time before a model is defined.

@AJamesPhillips
Copy link
Contributor

AJamesPhillips commented May 26, 2017

Something like this should work (thanks for the great library!):

var _ = require("lodash");
var Sequelize = require("sequelize");

var sequelize = new Sequelize(DATABASE, USERNAME, PASSWORD, config);

var UserFields = {
    uuid: {
        type: Sequelize.UUID,
        primaryKey: true,
        defaultValue: Sequelize.UUIDV4,
    },
    createdAt: {
        type: Sequelize.DATE(6),
    },
    updatedAt: {
        type: Sequelize.DATE(6),
    },
    deletedAt: {
        type: Sequelize.DATE(6),
    },
};

var USER_TABLE_NAME = "demo_user";

var NULLABLE_MODEL_FIELDS = {
    [USER_TABLE_NAME]: ["deletedAt"]
};

sequelize.beforeDefine(function (attributes, options) {

    // May break if name is defined by a string rather than object with {singular, plural}?
    var NULLABLE_FIELDS = NULLABLE_MODEL_FIELDS[options["name"]["singular"]] || {};
    _.keys(attributes).forEach(function (field_name) {

        var field_definition = attributes[field_name];
        if (!_.isString(field_definition) && !_.isUndefined(field_definition["type"])) {
            var nullable = _.includes(NULLABLE_FIELDS, field_name);
            // mutate attributes
            field_definition.allowNull = nullable;
        }
    });
});

var UserDb = sequelize.define(USER_TABLE_NAME, UserFields, DEFINE_OPTIONS);

@tsirolnik
Copy link

tsirolnik commented Jun 4, 2018

First of all, thanks for this great tool.
Now, I would like to add that maybe there should be considered an option to pass default arguments in the model definition so we wouldn't have to come up with beforeDefine stuff or setting allowNull per each column.

Something as in -

sequelize.define('user', {...}, {allowNull: false});

Which kinda exists via the Configuration option

@DevSide
Copy link

DevSide commented Aug 29, 2018

I ended up with that solution which won't apply to foreign keys. I feel annoyed to use tricks for consistent typing.

import { DataTypes } from 'sequelize';

export function disallowNull(attributes) {
    for(let attributeName in attributes) {
        const attrDef = attributes[attributeName];

        if (typeof attrDef === 'function' || attrDef instanceof DataTypes.ABSTRACT) {
            attributes[attributeName] = {
                type: attrDef,
                allowNull: false,
            };
        } else if (attrDef.allowNull !== true){
            attrDef.allowNull = false;
        }
    }

    return attributes;
}

// In the model file
sequelize.define('Resource', disallowNull({
  id: DataTypes.INTEGER,
  code: {
    type: DataTypes.STRING,
  },
  optional: {
    type: DataTypes.STRING,
    allowNull: true, // overrides default
  },
});

@d-luk
Copy link

d-luk commented Apr 2, 2020

Please re-open this feature request. It would be very useful to have an option to globally set allowNull: false as the default so we don't have to set it manually for every column.

@ephys
Copy link
Member

ephys commented Apr 16, 2022

Closing in favor of #14260

@ephys ephys closed this as completed Apr 16, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests