node-postgres $ 1 IS NULL错误
我正在使用node-postgres来编写一个web应用程序的后端,我遇到了这个错误:
error: could not determine data type of parameter $1 at Connection.parseE (/home/***/niche-api/node/node_modules/pg/lib/connection.js:539:11) at Connection.parseMessage (/home/***/niche-api/node/node_modules/pg/lib/connection.js:366:17) at Socket.<anonymous> (/home/***/niche-api/node/node_modules/pg/lib/connection.js:105:22) at emitOne (events.js:96:13) at Socket.emit (events.js:188:7) at readableAddChunk (_stream_readable.js:172:18) at Socket.Readable.push (_stream_readable.js:130:10) at TCP.onread (net.js:542:20)
我的查询的目标是接受从节点快递应用程序传入的查询参数,但不过滤数据库查询如果该参数不存在于api调用中。 例如,如果我的参数被称为variableType
并且它被设置为tmax
(例如, variableType=tmax
),那么数据库仅响应具有tmax的variableType的logging。 如果端点没有查询参数被命中,数据库将返回所有logging。
我的查询是:
SELECT * FROM variableTypes WHERE 1 = 1 AND ($1 IS NULL or $1 = variableTypeAbbreviation);
我这样称呼它:
app.get("/variables", function(req, res){ //get a list of the variables in the database var variableType = req.query.variableType if (variableType == undefined){ variableType = null; } var client = new pg.Client({ user: keys.user, password: keys.password, database: keys.dbName, hostname: keys.hostname }) client.connect(function(err){ if (err){ res.json(err); } var query = client.query({name: 'variableSelect', text: "SELECT * FROM variableTypes WHERE 1 = 1 AND ($1 IS NULL or $1 = variableTypeAbbreviation);", values:[variableType]}); console.log(query) query.on('row', function(row, result){ console.log("Got row") result.addRow(row) }) query.on('end', function(result){ console.log("Done.") res.json(result) client.end() })
我已经缩小到问题位于查询的部分($1 IS NULL)
。 我不知道该从哪里出发。 我写了一个类似的查询在python中(使用psycopg2),这工作,这使我认为它是更多的节点包有关。
query = select variableTypeID, variableType, variableTypeAbbreviation from variableTypes WHERE 1 = 1 AND (%(abbreviation)s is NULL or %(abbreviation)s LIKE lower(variableTypes.variableTypeAbbreviation) ) AND (%(fullName)s is NULL or %(fullName)s = variableTypes.variableType ) cursor.execute(query, {'fullName': fullName, 'abbreviation' : abbreviation})
任何意见非常感谢!
问题出在$1 IS NULL
,其中$1
被视为dynamic列名,由于数据库服务器实施的SQL注入防护措施,这在准备好的语句中是不允许的。
UPDATE
如果你想自由地格式化你的查询,同时也没有SQL注入的风险,请检查pg-promise 。 要正确格式化模式,表或列的名称 ,请参阅SQL名称 。