will / crystal-pg

a postgres driver for crystal
BSD 3-Clause "New" or "Revised" License
462 stars 77 forks source link

Unhandled exception: column "foo" does not exist (PQ::PQError) - How to insert into table without specifying all the columns #251

Closed frojnd closed 2 years ago

frojnd commented 2 years ago

Directly in psql cli I insert into table like this: INSERT INTO mytable (foo, bar) VALUES ('foo', 12);

my_table definition:

    Column    |  Type   | Collation | Nullable |             Default
--------------+---------+-----------+----------+---------------------------------
 id           | integer |           | not null | nextval('my_table_id_seq'::regclass)
 foo          | text    |           |          |
 bar          | integer |           | not null |
Indexes:
    "my_table_pkey" PRIMARY KEY, btree (id)

Note id being autoincremental and foo column being optional.

I tried to insert into my_table like this: db.exec "insert into my_table values (foo, bar)", "foo", 4

But I get:

Array(Bool | Float32 | Float64 | Int32 | Int64 | Slice(UInt8) | String | Time | Nil)
Unhandled exception: column "foo" does not exist (PQ::PQError)
  from lib/pg/src/pq/connection.cr:215:7 in 'handle_error'
  from lib/pg/src/pq/connection.cr:198:7 in 'handle_async_frames'
  from lib/pg/src/pq/connection.cr:174:7 in 'read'
  from lib/pg/src/pq/connection.cr:169:7 in 'read'
  from lib/pg/src/pq/connection.cr:447:31 in 'expect_frame'
  from lib/pg/src/pq/connection.cr:446:5 in 'expect_frame'
  from lib/pg/src/pg/statement.cr:18:5 in 'perform_query'
  from lib/pg/src/pg/statement.cr:35:14 in 'perform_exec'
  from lib/db/src/db/statement.cr:85:9 in 'perform_exec_and_release'
  from lib/db/src/db/statement.cr:70:7 in 'exec:args'
  from lib/db/src/db/pool_statement.cr:19:30 in 'exec:args'
  from lib/db/src/db/query_methods.cr:275:7 in 'exec'
  from .icr_DP-5JBbzEe7rSmH4Lcg5KQ.cr:27:1 in '__icr_exec__'
  from .icr_DP-5JBbzEe7rSmH4Lcg5KQ.cr:31:26 in '__crystal_main'
  from /usr/lib/crystal/crystal/main.cr:115:5 in 'main_user_code'
  from /usr/lib/crystal/crystal/main.cr:101:7 in 'main'
  from /usr/lib/crystal/crystal/main.cr:127:3 in 'main'
  from /usr/lib/libc.so.6 in '??'
  from /usr/lib/libc.so.6 in '__libc_start_main'

However it works if I insert like this: db.exec "insert into my_table values ($1, $2, $3)", 2, "foo", 4

bcardiff commented 2 years ago

There is a problem with the sql query

db.exec "insert into my_table values (foo, bar)", "foo", 4

Should be

db.exec "insert into my_table (foo, bar) values ($1, $2)", "foo", 4