TypeORM Parameterized Query Safety
Keep TypeORM queries injection-safe with parameter placeholders, typed find options, and a guard against unsafe raw SQL fragments.
Code
import { DataSource, Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
@Entity({ name: 'accounts' })
class Account {
@PrimaryGeneratedColumn() id!: number;
@Column() email!: string;
@Column() status!: string;
}
const dataSource = new DataSource({
type: 'postgres',
url: process.env.DATABASE_URL,
entities: [Account],
});
await dataSource.initialize();
const repo = dataSource.getRepository(Account);
async function searchByDomain(domain: string) {
// LIKE 模式里的通配符要转义,值仍走参数绑定
const escaped = domain.replace(/[\\%_]/g, (ch) => '\\' + ch);
return repo
.createQueryBuilder('account')
.where('account.email LIKE :pattern', { pattern: '%' + escaped + '%' })
.andWhere('account.status = :status', { status: 'active' })
.orderBy('account.id', 'ASC')
.limit(50)
.getMany();
}
function rejectUnsafeFragment(input: string): never {
if (/;|--|\/\*/.test(input)) {
throw new Error('suspicious SQL fragment rejected');
}
throw new Error('raw fragments are not allowed');
}
const matches = await searchByDomain('example.com');
console.log('accounts found:', matches.length);
await dataSource.destroy();Inside the snippet
searchByDomain binds every value through placeholders — LIKE :pattern with the domain’s %/_ wildcards pre-escaped, status = :status — while rejectUnsafeFragment throws on any ;, -- or /* in caller-supplied SQL text.
Await points sequence the asynchronous work; a rejection lands at the awaiting line. The import line is the dependency contract: DataSource, Entity, PrimaryGeneratedColumn, Column come from typeorm and nothing else. There is no validation gate in front of the Error — the throw fires whenever its line runs.
Configuration comes from the environment — it reads DATABASE_URL, so the same code switches behavior between environments without edits.
What to watch for
typeormmust be installed first — the snippet imports it directly.
Putting it to use
Entry signature: async function searchByDomain(domain: string)
The demo call searchByDomain('example.com') runs the parameterized query and prints accounts found: with the matched row count, after which dataSource.destroy() closes the pool.
Core lines
const escaped = domain.replace(/[\\%_]/g, (ch) => '\\' + ch);
throw new Error('suspicious SQL fragment rejected');
const matches = await searchByDomain('example.com');
Interactive Tools for This Topic
FAQ
- Does the snippet validate its input?
- No. There is no input validation in the snippet — the `Error` is raised unconditionally at its site, with no check in front of it.
- Do I need to install anything before running this?
- Yes: `typeorm` must be present in the project or the import fails at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.