LoginSignup
2
0

More than 1 year has passed since last update.

TypeORMでSQLiteを指定してQueryFailedError: SQLITE_CONSTRAINT: NOT NULL constraint failed エラーが出たときの対処法

Posted at

解決方法

解決策は4つあります。4つ目が本命です。

1. synchronizeをやめる

これでエラーはなくなるけど、エンティティが同期されなくなるので不便。。。

ormconfig.json
{
   "synchronize": true
}

2. カラムをnullableにする

これも根本的な解決じゃない。。。

entity/user.ts
@Column({ nullable: true })
name: string;

3. SQLiteを使わない

身も蓋もないですが、ありだと思います。

4. トランスパイルする

私の環境では、ts-nodeを使わないようにすると、エラーが解決されました。
以下の手順を行ってください。

STEP 1

tsconfig.jsonのCompilerOptionsに"skipLibCheck": trueを指定する。
これは、STEP3のtscコマンド実行時にエラーを表示させないためです。
基本的に推奨されるオプションではないので、エラーが出なかったら消してください。

tsconfig.json
{
   "compilerOptions": {
      "lib": [
         "es5",
         "es6"
      ],
      "module": "commonjs",
      "moduleResolution": "node",
      "outDir": "./build",
      "emitDecoratorMetadata": true,
      "experimentalDecorators": true,
      "sourceMap": true,
      "skipLibCheck": true
   }
}

STEP 2

ormconfig.jsonを以下のように書き換えます。
これは、トランスパイルしたJavaScriptを実行するためにパスを変更しています。

  • /src/build
  • .ts.js
ormconfig.json
{
   "type": "sqlite",
   "database": "database.sqlite",
   "synchronize": true,
   "logging": false,
   "entities": [
      "build/entity/**/*.js"
   ],
   "migrations": [
      "build/migration/**/*.js"
   ],
   "subscribers": [
      "build/subscriber/**/*.js"
   ],
   "cli": {
      "entitiesDir": "build/entity",
      "migrationsDir": "build/migration",
      "subscribersDir": "build/subscriber"
   }
}

STEP 3

tscでトランスパイルします。

$ tsc

すると、buildディレクトリに.jsファイルがたくさん書き出されるはずです。

実行できないときは、typescriptをグローバルにインストールしてください。

$ npm i -g typescript

STEP 4

nodeでトランスパイルしたJavaScriptファイルを実行します。

$ node build/index.js 

これでエラーが出なければOKです。

STEP 5

毎回コマンドを打ち込むのは大変なので、package.jsonに書き加えてスクリプトにします。

package.json
{
   ...
   "scripts": {
      "start": "tsc && node build/index.js",
   }
}

最初は実行できたけど、後でエラーになった場合

自分は遭遇してませんが、前の実行で出力したJavaScriptファイルが残っていると、エラーになる場合があるようです。その場合、以下のようなコマンドで実行前にbuildディレクトリを削除してください。

$ rm -r build && tsc && node dist/index.js

参考: [typeORM] NOT NULL constraint Failedなどのsynchronize回りのエラーの解決方法

発生したエラーの詳細

$ ts-node src/index.ts
QueryFailedError: SQLITE_CONSTRAINT: NOT NULL constraint failed: temporary_user.name
    at new QueryFailedError (/Users/src/error/QueryFailedError.ts:11:9)
    at Statement.handler (/Users/src/driver/sqlite/SqliteQueryRunner.ts:79:26) {
  errno: 19,
  code: 'SQLITE_CONSTRAINT',
  query: 'INSERT INTO "temporary_user"("id") SELECT "id" FROM "user"',
  parameters: []
}
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0