typeorm / typeorm

ORM for TypeScript and JavaScript. Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, SAP Hana, WebSQL databases. Works in NodeJS, Browser, Ionic, Cordova and Electron platforms.
http://typeorm.io
MIT License
34.26k stars 6.32k forks source link

Allow INSERT ... SELECT FROM #8538

Open Ginden opened 2 years ago

Ginden commented 2 years ago

Feature Description

Allow InsertQueryBuilder to use SELECT.

The Problem

Following code can't be generated using QueryBuilder

INSERT INTO foo(name)
SELECT "name" FROM other_table

The Solution

Obvious solution would be to use something like:

connection.getRepository(foo)
.insert()
.from(OtherTable, 'other_table')
.innerJoin(YetAnotherTable, 'yet_another_table', 'other_table ... = yet_another_table ...')
.where('...')

Easier to implement would be:

class InsertQueryBuilder<T = any> {
  from(queryBuilder: QueryBuilder<any>, alias?: string, columnNames?: (keyof T)[]);
}

and generate query like

INSERT INTO foo(name)
SELECT alias.name
FROM (
SELECT "name" FROM other_table
) alias

Considered Alternatives

Use other query builder library of construct query manually.

Additional Context

https://www.postgresql.org/docs/14/sql-insert.html

(redacted for clarity)

INSERT INTO table_name [ AS alias ] [ ( column_name [, ...] ) ]
    { query }

Relevant Database Driver(s)

DB Type Relevant
aurora-data-api yes
aurora-data-api-pg yes
better-sqlite3 yes
cockroachdb yes
cordova yes
expo yes
mongodb yes
mysql yes
nativescript yes
oracle yes
postgres yes
react-native yes
sap yes
sqlite yes
sqlite-abstract yes
sqljs yes
sqlserver yes

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

mortezaPRK commented 2 years ago

@Ginden I need this feature and also the one mentioned in #8542.

Do you plan to create a PR for it? if not, I'm ready to it.

Ginden commented 2 years ago

Do you plan to create a PR for it? if not, I'm ready to it.

You will probably be faster, because I will be busy at least until end of September.

PurpleTape commented 9 months ago

Any updates? 🥺🥺🥺

rohitkhatri commented 4 months ago

Any update on this?

VMolokostovEnergiAI commented 1 week ago

Anything so far?

Ginden commented 1 week ago

None, I'm not at company using TypeORM anymore.