Gestione dei valori null e undefined nelle condizioni where
Questa pagina è stata tradotta da PageTurner AI (beta). Non ufficialmente approvata dal progetto. Hai trovato un errore? Segnala problema →
Nelle condizioni 'WHERE', i valori null e undefined non sono strettamente validi in TypeORM.
TypeScript impedisce di passare valori null espliciti quando è attivo strictNullChecks in tsconfig.json. Tuttavia, il comportamento predefinito ignora i valori null rilevati a runtime. Analogamente, TypeScript permette valori undefined che vengono ignorati a runtime.
L'accettazione di valori null e undefined può causare risultati imprevisti e richiede cautela, specialmente quando i valori provengono da input utente senza adeguata validazione.
Ad esempio, Repository.findOneBy({ id: undefined }) restituisce la prima riga della tabella, mentre Repository.findBy({ userId: null }) non applica filtri e restituisce tutte le righe.
Il comportamento per null e undefined può essere personalizzato tramite l'opzione invalidWhereValuesBehavior nelle configurazioni della sorgente dati. Questa impostazione si applica a tutte le operazioni con condizioni WHERE, inclusi i metodi find, query builder e repository.
Il comportamento attuale cambierà nelle prossime versioni di TypeORM.
Consigliamo di impostare entrambi i comportamenti null e undefined su 'throw' per prepararsi a questi cambiamenti.
Comportamento Predefinito
Per impostazione predefinita, TypeORM ignora sia null che undefined nelle condizioni where. Ciò significa che includere una proprietà con valore null o undefined nella clausola WHERE la escluderà dalla query:
// Both queries will return all posts, ignoring the text property
const posts1 = await repository.find({
where: {
text: null,
},
})
const posts2 = await repository.find({
where: {
text: undefined,
},
})
Il metodo corretto per cercare valori nulli è usare l'operatore IsNull (dettagli in Opzioni di ricerca):
const posts = await repository.find({
where: {
text: IsNull(),
},
})
Configurazione
Personalizza la gestione di null e undefined tramite l'opzione invalidWhereValuesBehavior nella configurazione della connessione:
const dataSource = new DataSource({
// ... other options
invalidWhereValuesBehavior: {
null: "ignore" | "sql-null" | "throw",
undefined: "ignore" | "throw",
},
})
Opzioni per Null
Il comportamento per null può essere impostato su tre valori:
'ignore' (predefinito)
I valori JavaScript null nelle condizioni WHERE vengono ignorati e la proprietà è esclusa:
const dataSource = new DataSource({
// ... other options
invalidWhereValuesBehavior: {
null: "ignore",
},
})
// This will return all posts, ignoring the text property
const posts = await repository.find({
where: {
text: null,
},
})
'sql-null'
I valori JavaScript null vengono convertiti in condizioni SQL NULL:
const dataSource = new DataSource({
// ... other options
invalidWhereValuesBehavior: {
null: "sql-null",
},
})
// This will only return posts where the text column is NULL in the database
const posts = await repository.find({
where: {
text: null,
},
})
'throw'
I valori JavaScript null causano il lancio di un TypeORMError:
const dataSource = new DataSource({
// ... other options
invalidWhereValuesBehavior: {
null: "throw",
},
})
// This will throw an error
const posts = await repository.find({
where: {
text: null,
},
})
// Error: Null value encountered in property 'text' of a where condition.
// To match with SQL NULL, the IsNull() operator must be used.
// Set 'invalidWhereValuesBehavior.null' to 'ignore' or 'sql-null' in connection options to skip or handle null values.
Opzioni per Undefined
Il comportamento per undefined può essere impostato su due valori:
'ignore' (predefinito)
I valori JavaScript undefined nelle condizioni WHERE vengono ignorati e la proprietà è esclusa:
const dataSource = new DataSource({
// ... other options
invalidWhereValuesBehavior: {
undefined: "ignore",
},
})
// This will return all posts, ignoring the text property
const posts = await repository.find({
where: {
text: undefined,
},
})
'throw'
I valori JavaScript undefined causano il lancio di un TypeORMError:
const dataSource = new DataSource({
// ... other options
invalidWhereValuesBehavior: {
undefined: "throw",
},
})
// This will throw an error
const posts = await repository.find({
where: {
text: undefined,
},
})
// Error: Undefined value encountered in property 'text' of a where condition.
// Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in connection options to skip properties with undefined values.
Nota: si applica solo a valori undefined esplicitamente impostati, non a proprietà omesse.
Utilizzo Combinato
Puoi configurare entrambi i comportamenti indipendentemente per un controllo completo:
const dataSource = new DataSource({
// ... other options
invalidWhereValuesBehavior: {
null: "sql-null",
undefined: "throw",
},
})
Questa configurazione:
-
Trasforma i valori JavaScript
nullin SQLNULL -
Genera un errore per valori
undefined -
Ignora comunque le proprietà non fornite nella clausola WHERE
Questa combinazione è utile quando vuoi:
-
Essere esplicito nella ricerca di valori NULL nel database
-
Rilevare potenziali errori di programmazione dove valori undefined potrebbero essere introdotti nelle query
Si applica a tutte le operazioni WHERE
L'opzione invalidWhereValuesBehavior si applica a tutte le operazioni TypeORM con condizioni WHERE, non solo ai metodi find dei repository:
Costruttori di Query
// UpdateQueryBuilder
await dataSource
.createQueryBuilder()
.update(Post)
.set({ title: "Updated" })
.where({ text: null }) // Respects invalidWhereValuesBehavior
.execute()
// DeleteQueryBuilder
await dataSource
.createQueryBuilder()
.delete()
.from(Post)
.where({ text: null }) // Respects invalidWhereValuesBehavior
.execute()
// SoftDeleteQueryBuilder
await dataSource
.createQueryBuilder()
.softDelete()
.from(Post)
.where({ text: null }) // Respects invalidWhereValuesBehavior
.execute()
Metodi del Repository
// Repository.update()
await repository.update({ text: null }, { title: "Updated" }) // Respects invalidWhereValuesBehavior
// Repository.delete()
await repository.delete({ text: null }) // Respects invalidWhereValuesBehavior
// EntityManager.update()
await manager.update(Post, { text: null }, { title: "Updated" }) // Respects invalidWhereValuesBehavior
// EntityManager.delete()
await manager.delete(Post, { text: null }) // Respects invalidWhereValuesBehavior
// EntityManager.softDelete()
await manager.softDelete(Post, { text: null }) // Respects invalidWhereValuesBehavior
Tutte queste operazioni applicheranno in modo coerente le impostazioni configurate per invalidWhereValuesBehavior.