Skip to content

Commit

Permalink
use a non-cryptographic hash to generate unique statement names
Browse files Browse the repository at this point in the history
  • Loading branch information
drakkan committed Oct 8, 2023
1 parent 7fc908a commit aa55f6e
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 10 deletions.
8 changes: 4 additions & 4 deletions conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,9 @@ package pgx

import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"hash/fnv"
"strconv"
"strings"
"time"
Expand Down Expand Up @@ -318,8 +317,9 @@ func (c *Conn) Prepare(ctx context.Context, name, sql string) (sd *pgconn.Statem

var psName, psKey string
if name == sql {
digest := sha256.Sum256([]byte(sql))
psName = "stmt_" + hex.EncodeToString(digest[0:24])
h := fnv.New64a()
h.Write([]byte(sql))
psName = "stmt_" + strconv.FormatUint(h.Sum64(), 10)
psKey = sql
} else {
psName = name
Expand Down
2 changes: 0 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@ github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsI
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk=
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/puddle/v2 v2.2.0 h1:RdcDk92EJBuBS55nQMMYFXTxwstHug4jkhT5pq8VxPk=
github.com/jackc/puddle/v2 v2.2.0/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/jackc/puddle/v2 v2.2.1 h1:RhxXJtFG022u4ibrCSMSiu5aOq1i77R3OHKNJj77OAk=
github.com/jackc/puddle/v2 v2.2.1/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
Expand Down
9 changes: 5 additions & 4 deletions internal/stmtcache/stmtcache.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,18 @@
package stmtcache

import (
"crypto/sha256"
"encoding/hex"
"hash/fnv"
"strconv"

"github.com/jackc/pgx/v5/pgconn"
)

// StatementName returns a statement name that will be stable for sql across multiple connections and program
// executions.
func StatementName(sql string) string {
digest := sha256.Sum256([]byte(sql))
return "stmtcache_" + hex.EncodeToString(digest[0:24])
h := fnv.New64a()
h.Write([]byte(sql))
return "stmtcache_" + strconv.FormatUint(h.Sum64(), 10)
}

// Cache caches statement descriptions.
Expand Down

0 comments on commit aa55f6e

Please sign in to comment.