uptrace / bun

SQL-first Golang ORM
https://bun.uptrace.dev
BSD 2-Clause "Simplified" License
3.77k stars 230 forks source link

Bulk update excessive typecast #503

Open imraan-go opened 2 years ago

imraan-go commented 2 years ago

When using bulk() in NewUpdate(), bun tries to type cast all rows. But in postrgresql, type casting only the first column is enough. Also type casting primitive types such as string,int is not really needed. Here is an example query produced by bun:


WITH "_data" ( "id", "phone_number", "password", "reference_id", "fullname" ) AS (
    VALUES
        ( '47b2035b-fce2-4efb-b1ae-7c8882fd5a90' :: VARCHAR, '01716554433' :: VARCHAR, '' :: VARCHAR, 629 :: BIGINT, 'Abdullah' :: VARCHAR ),
        ( 'dbfa7e9e-6c55-4b22-b22f-bff2a8014b56' :: VARCHAR, '01716655661' :: VARCHAR, '' :: VARCHAR, 630 :: BIGINT, 'Abdullah' :: VARCHAR ),
        ( '8c6cd551-2705-4d23-8dab-c16704a60ce0' :: VARCHAR, '01700000002' :: VARCHAR, '' :: VARCHAR, 631 :: BIGINT, 'Rahman' :: VARCHAR ),
        ( 'da5ec352-7862-49ef-8e84-a673d604d567' :: VARCHAR, '0171665566' :: VARCHAR, '' :: VARCHAR, 0 :: BIGINT, '' :: VARCHAR ),
        ( '8139128e-4f41-445a-a756-4bd7019b6f86' :: VARCHAR, '01716965566' :: VARCHAR, '' :: VARCHAR, 0 :: BIGINT, '' :: VARCHAR ) 
    ) UPDATE "customers" AS "customer" 
    SET "reference_id" = _data."reference_id" 
FROM
    _data 
WHERE
    ( "customer"."id" = _data."id" )

This query can be shortened to:

WITH "_data" ( "id", "phone_number", "password", "reference_id", "fullname" ) AS (
    VALUES
        ( '47b2035b-fce2-4efb-b1ae-7c8882fd5a90'::uuid , '01716554433' , '' , 629 , 'Abdullah'  ),
        ( 'dbfa7e9e-6c55-4b22-b22f-bff2a8014b56' , '01716655661' , '' , 630 , 'Abdullah'  ),
        ( '8c6cd551-2705-4d23-8dab-c16704a60ce0' , '01700000002' , '' , 631 , 'Rahman'  ),
        ( 'da5ec352-7862-49ef-8e84-a673d604d567' , '0171665566' , '' , 0 , ''  ),
        ( '8139128e-4f41-445a-a756-4bd7019b6f86' , '01716965566' , '' , 0 , ''  ) 
    ) UPDATE "customers" AS "customer" 
    SET "cin7_reference_id" = _data."reference_id" 
FROM
    _data 
WHERE
    ( "customer"."id" = _data."id" )

Also when bun doesn't recognize a type, it tried to typecast it to some random type such as bigint,json etc.

vmihailenco commented 2 years ago

Also type casting primitive types such as string,int is not really needed

PR is welcome :)

it tried to typecast it to some random type such as bigint,json etc.

The type is not random - that is the type Bun auto-discovered from the Go column.

github-actions[bot] commented 1 day ago

This issue has been automatically marked as stale because it has not had activity in the last 30 days. If there is no update within the next 7 days, this issue will be closed.