使用 pgx 在 postgres 中创建用户 (SQLSTATE 42601)

Create User in postgres with pgx (SQLSTATE 42601)

我正在尝试在 postgres 中创建一个用户。当前正在尝试使用 https://github.com/jackc/pgx 作为连接到数据库的驱动程序。我有以下

package main

import (
    "context"
    "fmt"
    "os"

    "github.com/jackc/pgx/v4"
)

func main() {
    ctx := context.Background()
    conn, err := pgx.Connect(ctx, "host=localhost port=5432 user=postgres password=postgres dbname=postgres")
    if err != nil {
        panic(err)
    }
    defer conn.Close(ctx)

    // create user
    _, err = conn.Exec(ctx, "CREATE USER  WITH PASSWORD ", "moulick", "testpass")
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
}

但是我明白了 ERROR: syntax error at or near "" (SQLSTATE 42601)

我不明白这是什么问题?

“我不明白这里有什么问题?” -- 问题是 positional parameters 只能用于 values,而不是 标识符

A positional parameter reference is used to indicate a value that is supplied externally to an SQL statement.

您不能在 CREATE USER <user_name> 中使用位置参数,就像在 SELECT t.<column_name> FROM <table_name> AS t 中不能使用它们一样。

user_name := "moulick"
_, err = conn.Exec(ctx, "CREATE USER "+user_name+" WITH PASSWORD ", "testpass")
if err != nil {
    fmt.Println(err)
    os.Exit(1)
}

如果 user_name 不是硬编码的,而是来自未知的用户输入,您需要自己验证它以避免 SQL 注入的可能性。这不是一项艰巨的任务,因为 lexical structure of identifiers 仅限于一小组规则,如果您愿意,您可以进一步减少到更小的子集(例如,不允许变音符号和 non-Latin 字母):

SQL identifiers and key words must begin with a letter (a-z, but also letters with diacritical marks and non-Latin letters) or an underscore (_). Subsequent characters in an identifier or key word can be letters, underscores, digits (0-9), or dollar signs ($). Note that dollar signs are not allowed in identifiers according to the letter of the SQL standard, so their use might render applications less portable. The SQL standard will not define a key word that contains digits or starts or ends with an underscore, so identifiers of this form are safe against possible conflict with future extensions of the standard.