从打字稿到 postgres 的连接挂起 [英] Connection to postgres from typescript hangs

查看:61
本文介绍了从打字稿到 postgres 的连接挂起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从打字稿连接到 Postgres 数据库.我使用 sequelize-typescript 作为 ORM.我的问题是脚本卡在 await sequelize.sync(); 上.这是 sequelize.ts 文件:

import {Sequelize} from 'sequelize-typescript';从'./config/config'导入{配置};const c = config.dev;//实例化新的 Sequelize 实例!export const sequelize = new Sequelize({用户名":c.username,密码":c.密码,数据库":c.database,主机":c.host,方言:'postgres',存储:':内存:',});

这是模型类文件Product.ts:

 import {Table, Column, Model, HasMany, PrimaryKey, CreatedAt, UpdatedAt, ForeignKey} from 'sequelize-typescript';@桌子导出类 Product 扩展 Model{@柱子公共品牌:字符串;@柱子公价:数量;@柱子公开说明!:字符串;@柱子公共 imgUrl!: 字符串;@柱子公共类别:字符串;}

这是我使用 sequelize 的 server.ts:

 (async() => {等待 sequelize.addModels(V0MODELS);//它卡在这里等待 sequelize.sync();const app = express();常量端口 = 8100;//默认监听端口app.use(bodyParser.json());app.use(function(req, res, next) {res.header("Access-Control-Allow-Origin", "http://localhost:8100");res.header(Access-Control-Allow-Headers", Origin, X-Requested-With, Content-Type, Accept, Authorization");下一个();});app.use('/api/v0/', IndexRouter);//根 URI 调用app.get( "/", async ( req, res ) => {res.send(/api/v0/");});//启动服务器app.listen( 端口, () => {console.log(`服务器运行 http://localhost:${ 端口 }`);console.log(`请按 CTRL+C 停止服务器:)`);});})();

这里是 package.json 内容:

<代码>{名称":bagsshoes-server",版本":1.0.0",描述":",主":src/server.js",脚本":{开始":节点",tsc":tsc",dev":ts-node-dev --respawn --transpile-only ./src/server.ts",产品":tsc &&"节点./www/server.js",干净":rd/s/q www/>nul 2>&1|echo.>nul",构建":npm run clean &&"tsc&&cp -rf src/config www/config &&cp .npmrc www/.npmrc &&cp package.json www/package.json &&cd www &&zip -r Archive.zip .&&cd ..",测试":回声\"错误:未指定测试\"&&出口 1"},关键字":[],作者":Fahima Mokhtari",许可证":ISC",依赖关系":{@types/bcrypt":^3.0.0",@types/jsonwebtoken":^8.3.2",bcrypt":^3.0.6",正文解析器":^1.19.0",电子邮件验证器":^2.0.4",快递":^4.17.1",jsonwebtoken":^8.5.1",pg":^7.9.0",反射元数据":^0.1.13",续集":^5.3.5",sequelize-typescript":^0.6.9";},开发依赖":{@types/bluebird":^3.5.27",@types/express":^4.17.0",@types/node":^11.13.17",@types/sequelize":^4.27.44",@types/validator":^10.11.1",柴":^4.2.0",chai-http":^4.3.0",摩卡":^6.1.4",ts-node-dev":^1.0.0-pre.40",tslint":^5.18.0",打字稿":^3.5.3"}}

我尝试了 trycatch 但它没有显示任何错误,这让我更加困惑.任何帮助将不胜感激!

附注:

我使用的是 windows 和 Node V14.7.0

解决方案

注意

顶级域名!(脱脂时间太长)!答案又长又丰富!你可以略读!格式很好!

如果你很着急!您可以查看Authenticate部分、Sequelize-typescript(非sequelize)部分、Sequelize-typescript部分.

而且最好你可以直接进入地狱部分!了解 nodejs v14 HELL!(直接走到最后!好一点以上).

也检查一下 FIX (Postgres v14 HELL)

我开始了,不知不觉就发现自己写的太多了!

超级指南

基本上续集不应该只是挂!但是抛出一个错误!

查看代码源

通过查看 sync 代码

nvm 使用 v13现在使用节点 v13.14.0 (npm v6.14.4)coderhero@HeroStation  ~/Documents/coderhero/Dev/projects/Fahima-ecommerce   LuckyLook  npm run dev>bagshoes-server@1.0.0 dev/home/coderhero/Documents/coderhero/Dev/projects/Fahima-ecommerce>npx ts-node-dev src/server.ts[信息] 01:49:29 ts-node-dev 版本.1.0.0(使用 ts-node 版本 9.0.0,打字稿版本 4.0.5)配置::::{用户名:'fahima',密码:'123456',数据库:'fahimashop',主机:'本地主机',方言:'postgres'}你好呀 ::::执行(默认):SELECT 1+1 AS 结果连接已建立正在执行(默认):如果不存在产品",则创建表("id" SERIAL, "brand" TEXT, "price" DECIMAL, "description" VARCHAR(255), "imgUrl" VARCHAR(255), "category" VARCHAR(255), "createdAt"TIMESTAMP WITH TIME ZONE NOT NULL, updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL, PRIMARY KEY (id"));执行(默认):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 定义 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'和 t.relname = 'Products' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;服务器运行 http://localhost:8100按 CTRL+C 停止服务器,请:)

酷工作没问题

V14 和 v15 执行

v14

 coderhero@HeroStation  ~/Documents/coderhero/Dev/projects/Fahima-ecommerce   LuckyLook  node -vv14.15.0coderhero@HeroStation  ~/Documents/coderhero/Dev/projects/Fahima-ecommerce   LuckyLook  npm run dev>bagshoes-server@1.0.0 dev/home/coderhero/Documents/coderhero/Dev/projects/Fahima-ecommerce>npx ts-node-dev src/server.ts[信息] 02:07:35 ts-node-dev 版本.1.0.0(使用 ts-node 版本 9.0.0,打字稿版本 4.0.5)配置::::{用户名:'fahima',密码:'123456',数据库:'fahimashop',主机:'本地主机',方言:'postgres'}你好呀 ::::coderhero@HeroStation  ~/Documents/coderhero/Dev/projects/Fahima-ecommerce   LuckyLook 

还有哦!程序意外退出,没有错误输出!

V15

 coderhero@HeroStation  ~/Documents/coderhero/Dev/projects/Fahima-ecommerce   LuckyLook  nvm use v15现在使用节点 v15.0.1 (npm v7.0.3)coderhero@HeroStation  ~/Documents/coderhero/Dev/projects/Fahima-ecommerce   LuckyLook  npm run dev>bagshoes-server@1.0.0 dev>npx ts-node-dev src/server.ts[信息] 02:10:48 ts-node-dev 版本.1.0.0(使用 ts-node 版本 9.0.0,打字稿版本 4.0.5)配置::::{用户名:'fahima',密码:'123456',数据库:'fahimashop',主机:'本地主机',方言:'postgres'}你好呀 ::::coderhero@HeroStation  ~/Documents/coderhero/Dev/projects/Fahima-ecommerce   LuckyLook 

又是oppsii!程序意外退出,没有错误输出!

v14v15 也没有区别!这是V14 HELL.

简而言之

V14 HELL 是一个已知且很可能的原因!我猜 pg 模块有问题!v14 发生了一些变化并导致了这个问题!

简而言之!如果没有任何意义!如果您之前使用相同的代码!要做的第一件事!是用nodejs v13 还是v12 来检查!这可以让你远离精神错乱!谁会说nodejs的版本和新的会产生这样的问题!

这是什么问题!nodejs 中的 V14 HELL 是什么?

如果你和我一样想知道细节和发生了什么!?

使用节点 V14!api 发生了一些重大变化!也改变了很多东西!包括Openssl版本!

对于 postgres!还有 pg 模块!问题如此

更新到 v8

使用 node v15

再次运行

塔拉啊啊啊!而且效果非常好!

如果你没有使用 postgres!问题是v14 HELL!含义您使用 v13 进行了测试.它奏效了!然后尝试将您的数据库驱动程序升级到最新版本!

为什么 node v14 + 退出并且没有日志错误

还要提一下突破性的变化!pg 使进程在 connect() 调用 处退出.这就是它退出的原因!和日志是可以看到的!更详细的!这是怎么回事!Sequelize 有 postgres 方言实现!哪个用pg!还有PG客户端!建立联系!连接有一个 connect 事件!当它连接它发射它!并且因为节点 v14 将行为更改为以 open! 开头!流连接被跳过!并且将流视为已连接!哪里不对!而 connect 事件是直接发出的!当这种情况发生!客户端要么调用连接对象的requestSsl()startup() 方法!两者都会调用 this._stream.write.因为流没有连接!发生错误!这个错误不是catch!然后在续集驱动程序中的承诺!将保持悬而未决!然后事件循环变空了!Nodejs 默认行为只是退出!

您可以看到代码行的步骤:

为什么 nodejs 退出(未解决的承诺)

https://github.com/nodejs/node/issues/22088

节点无错误退出且不等待承诺(事件回调)

当 Promise 永不解析时会发生什么?

NVM

https://github.com/nvm-sh/nvm

如果您不知道 nvm 是什么!或者您没有使用 nvm.考虑使用它!因为它是一个非常有趣的工具!Nvm 是一个节点版本管理工具

随着nvm的变化,调试和测试到不同版本的nodejs!又快又轻!所以并行安装新版本的 nodejs!

关于 sequelize.sync() 的注意事项

请勿将其用于生产!或者根本没有!(大多数 ORM!和查询构建器 (knex.js) 使用迁移).

https://sequelize.org/master/manual/model-basics.html#synchronization-in-production

来自文档

<块引用>

如上图所示,sync({ force: true }) 和sync({ alter: true }) 可以破坏性操作.因此,不建议将它们用于生产级软件.相反,应该进行同步凭借迁移的先进理念,在Sequelize CLI.

I am trying to connect to a Postgres database from typescript. I'm using sequelize-typescript as an ORM. My problem is that the script gets stuck on await sequelize.sync();. Here's the sequelize.ts file:

import {Sequelize} from 'sequelize-typescript';
import { config } from './config/config';


const c = config.dev;

// Instantiate new Sequelize instance!
export const sequelize = new Sequelize({
  "username": c.username,
  "password": c.password,
  "database": c.database,
  "host":     c.host,

  dialect: 'postgres',
  storage: ':memory:',
});

And here's the model class file Product.ts:

  import {Table, Column, Model, HasMany, PrimaryKey, CreatedAt, UpdatedAt, ForeignKey} from 'sequelize-typescript';

@Table
export class Product extends Model<Product> {

    @Column
    public brand: string;

    @Column
    public price: number;

    @Column
    public description!: string;

    @Column
    public imgUrl!: string;

    @Column
    public cateogry: string;

  
}

Here's the server.ts where I use sequelize:

    (async () => {
 

  
  await sequelize.addModels(V0MODELS);

  //It get's stuck here
  await sequelize.sync();

  const app = express();
  const port =  8100; // default port to listen
  
  app.use(bodyParser.json());

  
  app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "http://localhost:8100");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
    next();
  });

  app.use('/api/v0/', IndexRouter);

  // Root URI call
  app.get( "/", async ( req, res ) => {
    res.send( "/api/v0/" );
  } );
  

  // Start the Server
  app.listen( port, () => {
      console.log( `server running http://localhost:${ port }` );
      console.log( `press CTRL+C to stop server, please :)` );
  } );
})();

And here is package.json content:

{
  "name": "bagsshoes-server",
  "version": "1.0.0",
  "description": "",
  "main": "src/server.js",
  "scripts": {
    "start": "node .",
    "tsc": "tsc",
    "dev": "ts-node-dev --respawn --transpile-only ./src/server.ts",
    "prod": "tsc && node ./www/server.js",
    "clean": "rd /s /q www/>nul 2>&1|echo.>nul",
    "build": "npm run clean && tsc && cp -rf src/config www/config && cp .npmrc www/.npmrc && cp package.json www/package.json && cd www && zip -r Archive.zip . && cd ..",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "Fahima Mokhtari",
  "license": "ISC",
  "dependencies": {
    "@types/bcrypt": "^3.0.0",
    "@types/jsonwebtoken": "^8.3.2",
    "bcrypt": "^3.0.6",
    "body-parser": "^1.19.0",
    "email-validator": "^2.0.4",
    "express": "^4.17.1",
    "jsonwebtoken": "^8.5.1",
    "pg": "^7.9.0",
    "reflect-metadata": "^0.1.13",
    "sequelize": "^5.3.5",
    "sequelize-typescript": "^0.6.9"
  },
  "devDependencies": {
    "@types/bluebird": "^3.5.27",
    "@types/express": "^4.17.0",
    "@types/node": "^11.13.17",
    "@types/sequelize": "^4.27.44",
    "@types/validator": "^10.11.1",
    "chai": "^4.2.0",
    "chai-http": "^4.3.0",
    "mocha": "^6.1.4",
    "ts-node-dev": "^1.0.0-pre.40",
    "tslint": "^5.18.0",
    "typescript": "^3.5.3"
  }
}

I tried try and catch but it showed no error, which got me confused even more. Any help will be greatly appreciated!

PS:

I'm using windows and Node V14.7.0

解决方案

NOTICE

TLDS! (TOO LONG DO SKIM)! The answer is long and rich! You can skim ! It's well formated!

If you are in big hurry! You can check Authenticate section, Sequelize-typescript (not sequelize) section, Sequelize-typescript section.

And better you can go directly to HELL section! Get to know nodejs v14 HELL! (Go directly to the end! Well a bit above).

Check too FIX (Postgres v14 HELL)

I started and before knowing i found myself wrote too much!

SUPER GUIDE

Basically sequelize should not just hang! But throw an error!

Looking at code source

By looking at sync code here

 async sync(options) {
    // ...

    // no models defined, just authenticate
    if (!models.length) {
      await this.authenticate(options);
    } else {
      for (const model of models) await model.sync(options);
    }
    if (options.hooks) {
      await this.runHooks('afterBulkSync', options);
    }
    return this;
  }

One easily can see the hanging possiblities!

Logging

To debug such anomalies first of all it's important to have good logging!

And you can check how to add logging here! Even though normally sequelize have the logging of the query activated by default!

https://sequelize.org/master/manual/getting-started.html#logging

const sequelize = new Sequelize('sqlite::memory:', {
  // Choose one of the logging options
  logging: console.log,                  // Default, displays the first parameter of the log function call
  logging: (...msg) => console.log(msg), // Displays all log function call parameters
  logging: false,                        // Disables logging
  logging: msg => logger.debug(msg),     // Use custom logger (e.g. Winston or Bunyan), displays the first parameter
  logging: logger.debug.bind(logger)     // Alternative way to use custom logger, displays all messages
});

Check the authentication

If not logging happen! That may means that sequelize didn't anything and is just hanging at the start! To test authentication and if the connection is working!

You can test with authenticate:

https://sequelize.org/master/manual/getting-started.html#testing-the-connection

try {
  console.log('Gonna authenticate'); // <== to make sure console.log is working and not overrided!
  await sequelize.authenticate();
  console.log('Connection has been established successfully.');
} catch (error) {
  console.error('Unable to connect to the database:', error);
}

If you get no logging! And Gonna authenticate printed just ok! Then the process is hanging on authenticate. Which suggest a problem in authentication!

Check your credentials

Make sure you didn't make any mistakes!

Check connectivity from psql or some other external client

  • If it doesn't work! It suggest a problem with postgres server! Or some config!
  • If it does work! Then the problem is in nodejs! And your program!

DON'T FORGET TO INSTALL THE POSTGRES DRIVER (Or your db driver)

As per the doc: https://sequelize.org/master/manual/getting-started.html#installing

# One of the following:
$ npm install --save pg pg-hstore # Postgres
$ npm install --save mysql2
$ npm install --save mariadb
$ npm install --save sqlite3
$ npm install --save tedious # Microsoft SQL Server

One of the commands! Make sure you didn't forget that!

Understanding what's happening and debugging better! (code source logging)

The best way to debug! And really determine where the problem is happening! Is by adding logs to the source code itself! A fast way for me is to directly do that on node_modules. I opened git on sequelize repo! Made a search! Determined the place of sync, authenticate, query! All reside in sequelize.js! you can check here! One can CTRL + F to get to the methods > authenticate( [add the (]. Any way! You can do the same in node_modules! And start adding logs! You'll know in which part the problem is happening! Which help you debug the problem!

The other way is to fork! And use your fork! And just work better!

But mmm! node_modules is a fast way! You can take a copy! too! To make sure you don't loose your logs! Once you update! At the end clean by just removing the whole module! And reinstall! Or just reverse the logs creation (undo)! I find it an interesting way for debugging!

But it should throw an error

Normally it should! By seeing the code source you can know better! Normally an error should be thrown! But if a process get hanged! And no error is thrown! Then you can expect a result like this! Here that can be the driver missing! Also make sure console.log. Is working all right! And the last thing! MMM may be it's a problem with nodejs itself (see the last section).

I'm using sequelize-typescript (not sequelize)

Very important to know! Sequelize-typescript is just a sequelize wrapper! That was there to add typescript support! It provide decorators and some features! Also From sequelize v5 ! Typescript is supported directly in sequelize! See here https://sequelize.org/master/manual/typescript.html sequelize-typescript in the latest version! Turned to use too the native declaration types of sequelize!

As sequelize-typecript wrap sequelize! Make sure to verify sequelize documentation!

To note too there is some people shouting: Don't use decorators! mmmm! mmm! And another mmmm! https://stackoverflow.com/a/60369189/7668448

Sequelize-typescript

If you are using sequelize-typescript make sure the version of sequelize-typescript and sequelize do match! As per there doc V5 of sequelize! I guess V6 too should do! And v1 for sequelize-typescript!

npm install sequelize@5 sequelize-typescript@1

And don't forget the typescript needed packages as per there doc!
https://www.npmjs.com/package/sequelize-typescript

(You can check and verify all those information in the doc itself)

Why to use sequelize-typescript ?

As already mentionned! Sequelize have native support for typescript starting from V5. As per here. So why use a wrapper above it! That use decorators too! (I'm not against decorators! Some are! As per here)

Ask yourself why ? Is there anything to sequelize-typescript! An important plus comparing to the native way ? If there is clear things! Please mention them in the comments! And i'll update! This section!

And if not! Native can be way better! A dependency or many in less!

Project configuration

tsconfig!

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es6",
        "moduleResolution": "node",
        "rootDir": "./src",
        "outDir": "./dist",
        "lib": [
            "es2015",
            "es2016",
            "dom"
        ],
        "declaration": true,
        "experimentalDecorators": true,
        "esModuleInterop": true
    },
    "include": [
        "src/**/*"
    ],
    "exclude": [
        "node_modules/**/*",
        "src/**/*.test.tsx",
        "src/**/*.story.tsx",
        "test/**/*"
    ]
}

Those are the two important things to add.

"experimentalDecorators": true,
"esModuleInterop": true

But that should not be your problem! Otherwise the project will throw compile errors!

HELL

Node js VERSION (V14 HELL)

And yea! That can be the cause! You may already used to have it work all right before! And then in a new computer or environment! It's not working any more!

Node version can be the problem! Node v15 and Node v14! That's a known problem! I myself encountered once with knex.js and postgres (knex.js is a query builder)! So you can see that is related! In my story the code was working all right on my laptop and old vps that we deployed in! But then i deployed on a windows rdp! And mmm! Boom! Then i pulled my hair for some time! I reflected and checked! There was no change! And then i came to hey! I only updated nodejs! And later i found that other people encountered the same thing! In short! It all started on nodejs v14 (i call this v14 HELL)! You can check my answer about it here

And apparently the same problem is always there with nodejs v15!

In the question of this thread! We confirmed that! In my desktop all worked well! Nodejs v12! And with my friend computer! It didn't! nodejs v14 and nodejs v15. Then i wanted to confirm! I installed nodejs v15 And caboom! BINGO! The execution just stop unexpectedly! No logging ! No error! In v12! All was working correctly! i had errors at first then i corrected them! And the server was up and running! And sequelize connected to the DB!

Here the executions

V12 and v13

I'm displaying v13! The same happen with v12!

nvm use v13
Now using node v13.14.0 (npm v6.14.4)
 coderhero@HeroStation  ~/Documents/coderhero/Dev/projects/Fahima-ecommerce   LuckyLook  npm run dev 

> bagsshoes-server@1.0.0 dev /home/coderhero/Documents/coderhero/Dev/projects/Fahima-ecommerce
> npx ts-node-dev src/server.ts

[INFO] 01:49:29 ts-node-dev ver. 1.0.0 (using ts-node ver. 9.0.0, typescript ver. 4.0.5)
config ::::
{
  username: 'fahima',
  password: '123456',
  database: 'fahimashop',
  host: 'localhost',
  dialect: 'postgres'
}
hi there ::::
Executing (default): SELECT 1+1 AS result
connection established
Executing (default): CREATE TABLE IF NOT EXISTS "Products" ("id"   SERIAL , "brand" TEXT, "price" DECIMAL, "description" VARCHAR(255), "imgUrl" VARCHAR(255), "category" VARCHAR(255), "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL, "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL, PRIMARY KEY ("id"));
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 = 'Products' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;
server running http://localhost:8100
press CTRL+C to stop server, please :)

Cool working no problem

V14 and v15 execution

v14

 coderhero@HeroStation  ~/Documents/coderhero/Dev/projects/Fahima-ecommerce   LuckyLook  node -v        
v14.15.0
 coderhero@HeroStation  ~/Documents/coderhero/Dev/projects/Fahima-ecommerce   LuckyLook  npm run dev

> bagsshoes-server@1.0.0 dev /home/coderhero/Documents/coderhero/Dev/projects/Fahima-ecommerce
> npx ts-node-dev src/server.ts

[INFO] 02:07:35 ts-node-dev ver. 1.0.0 (using ts-node ver. 9.0.0, typescript ver. 4.0.5)
config ::::
{
  username: 'fahima',
  password: '123456',
  database: 'fahimashop',
  host: 'localhost',
  dialect: 'postgres'
}
hi there ::::
 coderhero@HeroStation  ~/Documents/coderhero/Dev/projects/Fahima-ecommerce   LuckyLook  

And opps! The program is exiting unexpectedly with no error output!

V15

 coderhero@HeroStation  ~/Documents/coderhero/Dev/projects/Fahima-ecommerce   LuckyLook  nvm use v15    
Now using node v15.0.1 (npm v7.0.3)
 coderhero@HeroStation  ~/Documents/coderhero/Dev/projects/Fahima-ecommerce   LuckyLook  npm run dev

> bagsshoes-server@1.0.0 dev
> npx ts-node-dev src/server.ts

[INFO] 02:10:48 ts-node-dev ver. 1.0.0 (using ts-node ver. 9.0.0, typescript ver. 4.0.5)
config ::::
{
  username: 'fahima',
  password: '123456',
  database: 'fahimashop',
  host: 'localhost',
  dialect: 'postgres'
}
hi there ::::
 coderhero@HeroStation  ~/Documents/coderhero/Dev/projects/Fahima-ecommerce   LuckyLook  

And oppsii again! The program is exiting unexpectedly with no error output!

There is no difference too between v14 and v15! It's V14 HELL.

In short

The V14 HELL is a known and very probable cause! There is a problem with pg module i guess! Something changed on v14 and caused this problem!

In short short! If nothing is making any sense! And if your same code was working before! First thing to do! Is to check with nodejs v13 or v12! That can save you from insanity! Who would say the version of nodejs and a new one will create such a problem!

What is this problem! What is V14 HELL in nodejs ?

If like me you like to know the details and what did happen !?

With node V14! Some breaking changes happened on the api! Also many things were changed! Including Openssl version!

For postgres! And pg module! The problem was as described in this comment per this thread:

The initial readyState (a private/undocumented API that

pg uses) of net.Socket seems to have changed from 'closed' to 'open' in Node 14.

It’s hard to fix with perfect backwards compatibility, but I think I have a patch that’s close enough.

And as per this PR!

You can see the changes in this diffing

In short as mentioned! The behavior for onReadySate changed for net.Socket ! And the implemented solution was to not use onReadyState at all!

And as per this

Connection now always calls connect on its stream when connect is called on it.

Check this line

In the older version the connect was called only if the socket is on closed state! readyState usage is eliminated!

You can understand! Depending on the implementation! Many things may or not be affected by those core changes!

Relevant node changes

And because i wanted to see where the change happen! Here you go and can check

https://github.com/nodejs/node/pull/32272

One can check the log of changes too:

https://github.com/nodejs/node/blob/master/doc/changelogs/CHANGELOG_V14.md

FIX (Postgres v14 HELL)

As per my answer here.

Upgrade pg driver to >=8.0.3! You can simply upgrade to latest!

npm install pg@latest --save

And you can check for our problem in question

Old version at v7

Updating to v8

Running again with node v15

Taraaaaa! And it worked awesomely!

And if you are not using postgres! And the problem was v14 HELL! Meaning You tested with v13. And it worked! Then try to upgrade your db driver to latest!

Why node v14 + exit and no logging error

Also to mention the breaking changes! Made pg make the process exit at connect() call. And that's what made it exit! And logging was to be seen! In more detail for this! Here how it happened! Sequelize have the postgres dialect implementation! Which use pg! And pg client! create a connection! The connection have a connect event! When it connect it emit it! And because node v14 change the behavior to starting with open! The stream connection is skipped! And the stream is taken as connected! Where it is not! And the connect event is emitted directly! When that happen! The client either will call requestSsl() or startup() method of the connection object! And both will call this._stream.write. because the stream is not connected! An error happen! This error is not catch! Then the promise in sequelize driver! Will stay unresolved! And then the event loop get empty! Nodejs by default behavior just exit!

You can see the step through lines of code:

Why nodejs exit (unresolved promises)

https://github.com/nodejs/node/issues/22088

Node exits without error and doesn't await promise (Event callback)

what happens when a Promise never resolves?

NVM

https://github.com/nvm-sh/nvm

If you don't know what nvm is! Or you are not using nvm. Consider using it! As it's a very interesting tool! Nvm is a node version management tool!

With nvm changing, debugging and testing to and with different version of nodejs! Is quick and a breeze! And so installing new versions of nodejs in parallel!

Note about sequelize.sync()

Do not use it for production! Or at all! (Most of ORM! And query builder (knex.js) use migrations).

https://sequelize.org/master/manual/model-basics.html#synchronization-in-production

From the doc

As shown above, sync({ force: true }) and sync({ alter: true }) can be destructive operations. Therefore, they are not recommended for production-level software. Instead, synchronization should be done with the advanced concept of Migrations, with the help of the Sequelize CLI.

这篇关于从打字稿到 postgres 的连接挂起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆