Skip to content

Typescript unusable & Typescript tutorial completely broken "sequelize": "^6.3.4", #12603

Closed

Description

@stevemarksd
  • Is missing await sequelize.sync() before async function doStuffWithUser() {
  • Is missing to invoke doStuffWithUser function.
  • I also get a warning: (sequelize) Warning: PostgresSQL does not support 'INTEGER' with LENGTH, UNSIGNED or ZEROFILL. Plain 'INTEGER' will be used instead
  • Nothing is saved to the database: I get this error ValidationError [SequelizeValidationError]: notNull Violation: User.name cannot be null

After a long time figuring out what I had wrong in my code, I figured out why attributes are not saved to the db:

Let's say I copy the UserModel from the guide: (simplified)


  class User extends Model<UserAttributes, UserCreationAttributes>
    implements UserAttributes {
    public id!: number; // Note that the `null assertion` `!` is required in strict mode.
    public name!: string;
    public preferredName!: string | null; // for nullable fields

    // timestamps!
    public readonly createdAt!: Date;
    public readonly updatedAt!: Date;
  }

This will not save any attributes in the db. If I comment out the public name!: string; I get: INSERT INTO "users" ("name","createdAt","updatedAt") VALUES ($1,$2,$3) RETURNING "id","name","preferredName","createdAt","updatedAt"; (note that there is no preferredName)

image

Notice how preferredName is null. That's because is in the model!

Now If I comment both attributes: INSERT INTO "users" ("name","preferredName","createdAt","updatedAt") VALUES ($1,$2,$3,$4) RETURNING "id","name","preferredName","createdAt","updatedAt";


  class User extends Model<UserAttributes, UserCreationAttributes>
    implements UserAttributes {
    public id!: number; // Note that the `null assertion` `!` is required in strict mode.
   // public name!: string;
  //  public preferredName!: string | null; // for nullable fields

    // timestamps!
    public readonly createdAt!: Date;
    public readonly updatedAt!: Date;
  }

I get all keys!

image

As you can see this is unusable and I'm not even sure how to use it now with typescript.

I debugged a bit and seems like it applies correctly all attributes on a first pass, but somehow there is another pass and sets all attributes to null. I couldn't figure out who invoked the 2nd call to set to null (code a bit too dynamic).

Code to start sequelize instance

      this.sequelize = new Sequelize(
        databaseConfig.name,
        databaseConfig.username,
        databaseConfig.password,
        {
          host: databaseConfig.host,
          port: databaseConfig.port,
          dialect: 'postgres',
          pool: {
            max: 15,
            min: 1,
            acquire: 30000,
            idle: 10000,
          },
          logging: true,
        }
      )
      await this.sequelize.authenticate();

Issue Description

What are you doing?

Here is the link to the SSCCE for this issue: LINK-HERE

// You can delete this code block if you have included a link to your SSCCE above!
// MINIMAL, SELF-CONTAINED code here (SSCCE/MCVE/reprex)

What do you expect to happen?

I wanted Foo!

What is actually happening?

The output was Bar!

Output here

Additional context

Add any other context or screenshots about the feature request here.

Environment

  • Sequelize version: XXX
  • Node.js version: XXX
  • Operating System: XXX
  • If TypeScript related: TypeScript version: XXX

Issue Template Checklist

How does this problem relate to dialects?

  • I think this problem happens regardless of the dialect.
  • I think this problem happens only for the following dialect(s):
  • I don't know, I was using PUT-YOUR-DIALECT-HERE, with connector library version XXX and database version XXX

Would you be willing to resolve this issue by submitting a Pull Request?

  • Yes, I have the time and I know how to start.
  • Yes, I have the time but I don't know how to start, I would need guidance.
  • No, I don't have the time, although I believe I could do it if I had the time...
  • No, I don't have the time and I wouldn't even know how to start.

Activity

  1. changed the title [-]Typescript tutorial completely broken `"sequelize": "^6.3.4",`[/-] [+]Typescript unusable & Typescript tutorial completely broken `"sequelize": "^6.3.4",`[/+] on Aug 10, 2020
  2. github-actions commented on Oct 31, 2021

    @github-actions
    Contributor

    This issue has been automatically marked as stale because it has been open for 7 days without activity. It will be closed if no further activity occurs. If this is still an issue, just leave a comment or remove the "stale" label. 🙂

  3. ilijapuaca commented on Nov 8, 2021

    @ilijapuaca

    This prohibits usage of sequelize with TS which is highlighted by the TS docs example not working. Not sure if this is tracked in another ticket but if not it should stay open?

  4. WikiRik commented on Nov 9, 2021

    @WikiRik
    Member

    @ilijapuaca I am also not sure if this is tracked in another ticket, but I'll reopen it just to be sure. Thanks for the reply!

  5. reopened this on Nov 9, 2021
  6. github-actions commented on Nov 24, 2021

    @github-actions
    Contributor

    This issue has been automatically marked as stale because it has been open for 14 days without activity. It will be closed if no further activity occurs within the next 14 days. If this is still an issue, just leave a comment or remove the "stale" label. 🙂

  7. ilijapuaca commented on Nov 24, 2021

    @ilijapuaca

    Still relevant, not stale

  8. added
    docs
    typescript
    and removed on Nov 24, 2021
  9. knoid commented on Dec 29, 2021

    @knoid
    Contributor

    Same problem here, this is happening since typescript v4.3.2. I've read the release notes but nothing stands out to me.

  10. ephys commented on Dec 29, 2021

    @ephys
    Member

    The fields disappearing looks like a duplicate of #10579 (with potential solution #10579 (comment))

    The rest I'm unsure about and can't help without a SSCCE or a repo we can look at and find what's wrong

  11. knoid commented on Dec 29, 2021

    @knoid
    Contributor

    @ephys You can find an example here: https://github.com/knoid/sequelize-test-12603

    All I did was a typescript project where index.ts is a copy of ModelInit.ts.

  12. ephys commented on Dec 29, 2021

    @ephys
    Member

    Thanks, took at look at it :)

    So the warning PostgresSQL does not support 'INTEGER' with LENGTH, UNSIGNED or ZEROFILL. Plain 'INTEGER' will be used instead is correct. The example uses mysql which supports unsigned integers while your example uses postgres, which does not. It's just a warning and removing .UNSIGNED removes the warning.

    Not specifying await sequelize.sync() is not incorrect. You should avoid it in production for instance, and it's not relevant to the typescript example. It's also normal that it doesn't invoke doStuffWithUser. It's only a typing example.

    I'm going to work on the TS docs a bit so I'll include these anyway so the example runs.

    tried launching using npm start and it worked, so looks like it works using tsc & ts-node. #10579 is still just a babel issue.

    I'm keeping the issue open as a documentation issue. I'll tackle it along with #10579

  13. self-assigned this
    on Dec 29, 2021
  14. knoid commented on Dec 29, 2021

    @knoid
    Contributor

    ok, I may have skipped some explaining. This is the output I get by running npm start.

    > [email protected] start
    > ts-node index.ts
    
    (sequelize) Warning: PostgresSQL does not support 'INTEGER' with LENGTH, UNSIGNED or ZEROFILL. Plain 'INTEGER' will be used instead.
    >> Check: http://www.postgresql.org/docs/9.4/static/datatype.html
    SQL: Executing (default): CREATE TABLE IF NOT EXISTS "users" ("id"  SERIAL , "name" VARCHAR(128) NOT NULL, "preferredName" VARCHAR(128), "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL, "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL, PRIMARY KEY ("id")); NaN
    SQL: Executing (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND t.relkind = 'r' and t.relname = 'users' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname; NaN
    SQL: Executing (default): CREATE TABLE IF NOT EXISTS "projects" ("id"  SERIAL , "ownerId" INTEGER NOT NULL REFERENCES "users" ("id") ON DELETE CASCADE ON UPDATE CASCADE, "name" VARCHAR(128) NOT NULL, "description" VARCHAR(128), "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL, "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL, PRIMARY KEY ("id")); NaN
    SQL: Executing (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND t.relkind = 'r' and t.relname = 'projects' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname; NaN
    SQL: Executing (default): CREATE TABLE IF NOT EXISTS "address" ("id"   SERIAL , "userId" INTEGER, "address" VARCHAR(128) NOT NULL, "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL, "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL, "UserId" INTEGER REFERENCES "users" ("id") ON DELETE SET NULL ON UPDATE CASCADE, PRIMARY KEY ("id")); NaN
    SQL: Executing (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND t.relkind = 'r' and t.relname = 'address' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname; NaN
    SQL: Executing (default): CREATE TABLE IF NOT EXISTS "notes" ("id"  SERIAL , "title" VARCHAR(64) DEFAULT 'Unnamed Note', "content" VARCHAR(4096) NOT NULL, "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL, "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL, PRIMARY KEY ("id")); NaN
    SQL: Executing (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND t.relkind = 'r' and t.relname = 'notes' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname; NaN
    SQL: Executing (default): INSERT INTO "users" ("id","name","preferredName","createdAt","updatedAt") VALUES (DEFAULT,$1,$2,$3,$4) RETURNING "id","name","preferredName","createdAt","updatedAt"; "Johnny", "John", "2021-12-29 20:23:14.321 +00:00", "2021-12-29 20:23:14.321 +00:00" NaN
    undefined undefined undefined
    /home/knoid/sequelize-test-project/index.ts:220
      const project = await newUser.createProject({
                                    ^
    TypeError: newUser.createProject is not a function
        at doStuffWithUser (/home/knoid/sequelize-test-project/index.ts:220:33)
        at processTicksAndRejections (node:internal/process/task_queues:96:5)
        at async main (/home/knoid/sequelize-test-project/index.ts:237:3)
    

    The line that says undefined undefined undefined is line 218 where it's trying to access newUser's properties and it just gets undefined for every one. It then fails on the following line because createProject is also undefined and it's trying to invoke it.

    To make this all work, I previously created a postgres database called sequelize-test as you can see from the credentials on line 19.

    Thanks for everything, I hope this clarifies the error we are getting.

  15. ephys commented on Dec 29, 2021

    @ephys
    Member

    Hmm sorry I missed something I changed during my tests.

    Set "target": "esnext", to "target": "ES2021", in tsconfig.json

    If you're going to use esnext, add declare in front of the fields you're only declaring for typing:

    image

    image

    I'm going to add all that to the documentation

  16. knoid commented on Dec 29, 2021

    @knoid
    Contributor

    That's interesting! You can see my latest commit with the appropriate changes. I didn't know about this declare keyword. Now it all works. Thanks!

  17. ephys commented on Jan 2, 2022

    @ephys
    Member

    Closed by #13877

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

docstypescript

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions