How to convert MySQL-style question mark `?` bound parameters to Postgres-style `$1` bound parameter

倖福魔咒の 提交于 2019-12-06 13:24:21

Is there some way of having node-postgres accept the question marks instead?

NO. And there is no direct correspondence between ? and $1 syntax, because the latter implies parameter re-use, while ? doesn't allow it. For example, using ? ? ? implies that you have 3 formatting parameters, while $1 $2 $2 implies that you have two formatting parameters.

or an utility that can convert to postgres style params?

Not likely, since there is no direct correspondence, the conversion is possible only one-way, which would make such an utility fairly useless. You can replace everything yourself, with a single regular expression, replacing each ? with $ + index + 1.

I don't want to convert all my existing SQL from ? to postgres-style operators like $1.

You don't really have much choice in this. It has to be done. Besides, $1 is way more flexible than ?, due to parameter re-use, plus optional extensions. For example, pg-promise extends them very nicely, with various formatting modifiers that are needed frequently: ^, ~, :json, :csv, etc...

Note that some sort of Regex-based hack is not acceptable because question marks can be inside quotes, or backslash escaped to any depth.

You will likely spend less time converting your SQL by hand, than the time to write an utility for the one-way proper conversion.

Actually converting ? to $1, $2 etc will always work. Converting $1, $2 back to ? won't work if you've repeated parameters.

It would be valuable for those porting software from MySQL and others if PG supported the ? parameter stub.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!