ronantakizawa/codereview-bench huggingface dataset:
Repository: prisma/prisma
File: packages/driver-adapter-utils/src/types.ts (TypeScript)

Code before:
  | {
      kind: 'SocketTimeout'
    }
  | {
      kind: 'InconsistentColumnData'
      cause: string
    }
  | {
      kind: 'TransactionAlreadyClosed'
      cause: string
    }
  | {
      kind: 'postgres'
      code: string
      severity: string
      message: string
      detail: string | undefined
      column: string | undefined
      hint: string | undefined
    }
  | {
      kind: 'mysql'
      code: number
      message: string
      state: string
      cause: string | undefined
    }
  | {
      kind: 'sqlite'
      /**
       * Sqlite extended error code: https://www.sqlite.org/rescode.html
       */
      extendedCode: number
      message: string
    }
  | {
      kind: 'mssql'
      code: number
      message: string
    }

export type ConnectionInfo = {
  schemaName?: string
  maxBindValues?: number
  supportsRelationJoins: boolean
}

export type Provider = 'mysql' | 'postgres' | 'sqlite' | 'sqlserver'

// Current list of official Prisma adapters
// This list might get outdated over time.

Review comment (suggestion):
this being a required field is causing type errors, it should probably be `cause?: string`

Code after:
  | {
      kind: 'SocketTimeout'
    }
  | {
      kind: 'InconsistentColumnData'
      cause: string
    }
  | {
      kind: 'TransactionAlreadyClosed'
      cause: string
    }
  | {
      kind: 'postgres'
      code: string
      severity: string
      message: string
      detail: string | undefined
      column: string | undefined
      hint: string | undefined
    }
  | {
      kind: 'mysql'
      code: number
      message: string
      state: string
      cause?: string
    }
  | {
      kind: 'sqlite'
      /**
       * Sqlite extended error code: https://www.sqlite.org/rescode.html
       */
      extendedCode: number
      message: string
    }
  | {
      kind: 'mssql'
      code: number
      message: string
    }

export type ConnectionInfo = {
  schemaName?: string
  maxBindValues?: number
  supportsRelationJoins: boolean
}

export type Provider = 'mysql' | 'postgres' | 'sqlite' | 'sqlserver'

// Current list of official Prisma adapters
// This list might get outdated over time.
Repository: prisma/prisma
File: packages/adapter-d1/src/conversion.ts (TypeScript)

Code before:
function inferNumberType(_: number): ColumnType {
  return ColumnTypeEnum.UnknownNumber
}

function inferObjectType(value: Object): ColumnType {
  if (value instanceof Array) {
    return ColumnTypeEnum.Bytes
  }
  throw new UnexpectedTypeError(value)
}

class UnexpectedTypeError extends Error {
  name = 'UnexpectedTypeError'
  constructor(value: unknown) {
    const type = typeof value
    const repr = type === 'object' ? JSON.stringify(value) : String(value)
    super(`unexpected value of type ${type}: ${repr}`)
  }
}

export function mapRow<A>(result: (A | ResultValue)[], columnTypes: ColumnType[]): (A | ResultValue)[] {
  for (let i = 0; i < result.length; i++) {
    const value = result[i]

    if (value instanceof ArrayBuffer) {
      result[i] = Buffer.from(value)
      continue
    }

    if (
      typeof value === 'number' &&
      (columnTypes[i] === ColumnTypeEnum.Int32 || columnTypes[i] === ColumnTypeEnum.Int64) &&
      !Number.isInteger(value)
    ) {
      result[i] = Math.trunc(value)
      continue
    }

    if (typeof value === 'number' && columnTypes[i] === ColumnTypeEnum.Text) {
      result[i] = value.toString()
      continue
    }

    if (typeof value === 'bigint') {
      result[i] = value.toString()
      continue
    }

    if (columnTypes[i] === ColumnTypeEnum.Boolean) {
      result[i] = JSON.parse(value as any)
    }

Review comment (suggestion):
I think it should be `new Uint8Array(value)`, we try to not use `Buffer` much anymore and we have even changed the public API in Prisma 6 to accept and return `Uint8Array`s. Especially here, since it's an adapter for Cloudflare D1, I'd expect a standard JS type and not a Node.js specific one.

Code after:
function inferNumberType(_: number): ColumnType {
  return ColumnTypeEnum.UnknownNumber
}

function inferObjectType(value: Object): ColumnType {
  if (value instanceof Array) {
    return ColumnTypeEnum.Bytes
  }
  throw new UnexpectedTypeError(value)
}

class UnexpectedTypeError extends Error {
  name = 'UnexpectedTypeError'
  constructor(value: unknown) {
    const type = typeof value
    const repr = type === 'object' ? JSON.stringify(value) : String(value)
    super(`unexpected value of type ${type}: ${repr}`)
  }
}

export function mapRow<A>(result: (A | ResultValue)[], columnTypes: ColumnType[]): (A | ResultValue)[] {
  for (let i = 0; i < result.length; i++) {
    const value = result[i]

    if (value instanceof ArrayBuffer) {
      result[i] = new Uint8Array(value)
      continue
    }

    if (
      typeof value === 'number' &&
      (columnTypes[i] === ColumnTypeEnum.Int32 || columnTypes[i] === ColumnTypeEnum.Int64) &&
      !Number.isInteger(value)
    ) {
      result[i] = Math.trunc(value)
      continue
    }

    if (typeof value === 'number' && columnTypes[i] === ColumnTypeEnum.Text) {
      result[i] = value.toString()
      continue
    }

    if (typeof value === 'bigint') {
      result[i] = value.toString()
      continue
    }

    if (columnTypes[i] === ColumnTypeEnum.Boolean) {
      result[i] = JSON.parse(value as any)
    }
Repository: prisma/prisma
File: packages/adapter-mssql/src/connection-string.ts (TypeScript)

Code before:
  return undefined
}

/**
 * Splits a connection string by semicolons while respecting curly brace escaping.
 * Values wrapped in curly braces like {value} are treated as literals where
 * semicolons and equals signs are not treated as delimiters.
 *
 * Important: Curly braces are only treated as quote characters when { is the
 * FIRST character of a value (after the = sign). This matches tedious behavior.
 *
 * @param str The string to split
 * @returns Array of parts split by semicolon (outside of curly braces)
 */
function splitRespectingBraces(str: string): string[] {
  const parts: string[] = []
  let current = ''
  let braceDepth = 0
  let valueStartIndex = -1

  for (let i = 0; i < str.length; i++) {
    const char = str[i]

    if (char === '=') {
      current += char
      valueStartIndex = i + 1
    } else if (char === '{') {
      // Only treat { as opening brace if it's the first character of a value
      const isFirstCharOfValue = i === valueStartIndex
      if (isFirstCharOfValue) {
        braceDepth++
      }
      current += char
    } else if (char === '}') {
      if (braceDepth > 0) {
        braceDepth--
      }
      current += char
    } else if (char === ';' && braceDepth === 0) {
      parts.push(current)
      current = ''
      valueStartIndex = -1
    } else {
      current += char
    }
  }

  if (current) {
    parts.push(current)
  }


Review comment (security):
I think we should wrap `valueStartIndex = i + 1` with `if (braceDepth === 0)` to avoid treating escaped `=` as a legitimate value prefixx

Code after:
  let valueStartIndex = -1

  for (let i = 0; i < str.length; i++) {
    const char = str[i]

    if (char === '=') {
      current += char
      if (braceDepth === 0) {
        valueStartIndex = i + 1
      }
    } else if (char === '{') {
      // Only treat { as opening brace if it's the first character of a value
      const isFirstCharOfValue = i === valueStartIndex
      if (isFirstCharOfValue) {
        braceDepth++
      } else if (braceDepth > 0) {
        throw new Error(`Malformed connection string: nested '{' braces are not supported`)
      }
      current += char
    } else if (char === '}') {
      if (braceDepth > 0) {
        braceDepth--
      }
      current += char
    } else if (char === ';' && braceDepth === 0) {
      parts.push(current)
      current = ''
      valueStartIndex = -1
    } else {
      current += char
    }
  }

  if (current) {
    parts.push(current)
  }

  if (braceDepth !== 0) {
    throw new Error(`Malformed connection string: unclosed '{' brace (braceDepth=${braceDepth})`)
  }

  return parts
}

/**
 * Extracts the value from a parameter, removing curly braces if present.
 * If the value is wrapped in curly braces like {value}, returns value.
 * Otherwise returns the value as-is.
 * @param value The value to process
 * @returns The unescaped value
 */
Repository: prisma/prisma
File: packages/client-engine-runtime/src/interpreter/query-interpreter.ts (TypeScript)

Code before:
          parentRecord[joinExpr.parentField].push(childRecord)
        }
      }
    }
  }

  return parentRecords
}

function inferKeyCasts(rows: unknown[], keys: string[]): KeyCast[] {
  function getKeyCast(type: string): KeyCast | undefined {
    switch (type) {
      case 'number':
        return Number
      case 'string':
        return String
      case 'boolean':
        return Boolean
      case 'bigint':
        return BigInt as KeyCast
      default:
        return
    }
  }

  const keyCasts: KeyCast[] = []
  let keysFound = 0
  for (const parent of rows) {
    const parentRecord = asRecord(parent)
    for (const [i, key] of keys.entries()) {
      if (parentRecord[key] !== null && keyCasts[i] === undefined) {
        const keyCast = getKeyCast(typeof parentRecord[key])
        if (keyCast !== undefined) {
          keyCasts[i] = keyCast
        }
        keysFound++
      }
    }
    if (keysFound === keys.length) {
      break
    }
  }

  return keyCasts
}

function evalFieldInitializer(
  initializer: FieldInitializer,
  lastInsertId: string | undefined,
  scope: ScopeBindings,
  generators: GeneratorRegistrySnapshot,

Review comment (suggestion):
```suggestion
  const keyCasts: KeyCast[] = Array.from({ length: keys.length })
```

Code after:
          parentRecord[joinExpr.parentField].push(childRecord)
        }
      }
    }
  }

  return parentRecords
}

function inferKeyCasts(rows: unknown[], keys: string[]): KeyCast[] {
  function getKeyCast(type: string): KeyCast | undefined {
    switch (type) {
      case 'number':
        return Number
      case 'string':
        return String
      case 'boolean':
        return Boolean
      case 'bigint':
        return BigInt as KeyCast
      default:
        return
    }
  }

  const keyCasts: KeyCast[] = Array.from({ length: keys.length })
  let keysFound = 0
  for (const parent of rows) {
    const parentRecord = asRecord(parent)
    for (const [i, key] of keys.entries()) {
      if (parentRecord[key] !== null && keyCasts[i] === undefined) {
        const keyCast = getKeyCast(typeof parentRecord[key])
        if (keyCast !== undefined) {
          keyCasts[i] = keyCast
        }
        keysFound++
      }
    }
    if (keysFound === keys.length) {
      break
    }
  }

  return keyCasts
}

function evalFieldInitializer(
  initializer: FieldInitializer,
  lastInsertId: string | undefined,
  scope: ScopeBindings,
  generators: GeneratorRegistrySnapshot,
Repository: prisma/prisma
File: packages/client-engine-runtime/src/utils.ts (TypeScript)

Code before:
import { Decimal } from '@prisma/client-runtime-utils'

export type DeepReadonly<T> = T extends undefined | null | boolean | string | number | Function
  ? T
  : T extends Array<infer U>
    ? ReadonlyArray<DeepReadonly<U>>
    : unknown extends T
      ? unknown
      : { readonly [K in keyof T]: DeepReadonly<T[K]> }

export type DeepUnreadonly<T> = T extends undefined | null | boolean | string | number | Function
  ? T
  : T extends ReadonlyArray<infer U>
    ? Array<DeepUnreadonly<U>>
    : unknown extends T
      ? unknown
      : { -readonly [K in keyof T]: DeepUnreadonly<T[K]> }

// Copied over to avoid the heavy dependency on `@prisma/internals` with its
// transitive dependencies that are not needed for other query plan executor
// implementations outside of Prisma Client (e.g. test executor for query
// engine tests and query plan executor for Accelerate) that also depend on
// `@prisma/client-engine-runtime`.
export function assertNever(_: never, message: string): never {
  throw new Error(message)
}

/**

Review comment (suggestion):
```suggestion
export type DeepReadonly<T> = T extends undefined | null | boolean | string | number | symbol | Function | Date
```

Code after:
import { Decimal } from '@prisma/client-runtime-utils'

export type DeepReadonly<T> = T extends undefined | null | boolean | string | number | symbol | Function | Date
  ? T
  : T extends Array<infer U>
    ? ReadonlyArray<DeepReadonly<U>>
    : unknown extends T
      ? unknown
      : { readonly [K in keyof T]: DeepReadonly<T[K]> }

export type DeepUnreadonly<T> = T extends undefined | null | boolean | string | number | symbol | Function | Date
  ? T
  : T extends ReadonlyArray<infer U>
    ? Array<DeepUnreadonly<U>>
    : unknown extends T
      ? unknown
      : { -readonly [K in keyof T]: DeepUnreadonly<T[K]> }

// Copied over to avoid the heavy dependency on `@prisma/internals` with its
// transitive dependencies that are not needed for other query plan executor
// implementations outside of Prisma Client (e.g. test executor for query
// engine tests and query plan executor for Accelerate) that also depend on
// `@prisma/client-engine-runtime`.
export function assertNever(_: never, message: string): never {
  throw new Error(message)
}

/**
Repository: prometheus/alertmanager
File: notify/telegram/telegram.go (Go)

Code before:
		tmpl = notify.TmplText(n.tmpl, data, &err)
	)

	if n.conf.ParseMode == "HTML" {
		tmpl = notify.TmplHTML(n.tmpl, data, &err)
	}

	key, ok := notify.GroupKey(ctx)
	if !ok {
		return false, fmt.Errorf("group key missing")
	}

	messageText, truncated := notify.TruncateInRunes(tmpl(n.conf.Message), maxMessageLenRunes)
	if truncated {
		level.Warn(n.logger).Log("msg", "Truncated message", "alert", key, "max_runes", maxMessageLenRunes)
	}

	n.client.Token, err = n.getBotToken()
	if err != nil {
		return true, err
	}

	message, err := n.client.Send(telebot.ChatID(n.conf.ChatID), messageText, &telebot.SendOptions{
		DisableNotification:   n.conf.DisableNotifications,
		DisableWebPagePreview: true,
		ThreadID:              int(n.conf.MessageTheadID),
	})
	if err != nil {
		return true, err
	}
	level.Debug(n.logger).Log("msg", "Telegram message successfully published", "message_id", message.ID, "chat_id", message.Chat.ID)

	return false, nil
}

func createTelegramClient(apiURL, parseMode string, httpClient *http.Client) (*telebot.Bot, error) {
	bot, err := telebot.NewBot(telebot.Settings{
		URL:       apiURL,
		ParseMode: parseMode,
		Client:    httpClient,
		Offline:   true,
	})
	if err != nil {
		return nil, err
	}

	return bot, nil
}

func (n *Notifier) getBotToken() (string, error) {
	if len(n.conf.BotTokenFile) > 0 {

Review comment (suggestion):
This doesn't compile I'm afraid:

```go
notify/telegram/telegram.go:96:37: n.conf.MessageTheadID undefined (type *"github.com/prometheus/alertmanager/config".TelegramConfig has no field or method MessageTheadID)
```

Code after:
		tmpl = notify.TmplText(n.tmpl, data, &err)
	)

	if n.conf.ParseMode == "HTML" {
		tmpl = notify.TmplHTML(n.tmpl, data, &err)
	}

	key, ok := notify.GroupKey(ctx)
	if !ok {
		return false, fmt.Errorf("group key missing")
	}

	messageText, truncated := notify.TruncateInRunes(tmpl(n.conf.Message), maxMessageLenRunes)
	if truncated {
		level.Warn(n.logger).Log("msg", "Truncated message", "alert", key, "max_runes", maxMessageLenRunes)
	}

	n.client.Token, err = n.getBotToken()
	if err != nil {
		return true, err
	}

	message, err := n.client.Send(telebot.ChatID(n.conf.ChatID), messageText, &telebot.SendOptions{
		DisableNotification:   n.conf.DisableNotifications,
		DisableWebPagePreview: true,
		ThreadID:              n.conf.MessageThreadID,
	})
	if err != nil {
		return true, err
	}
	level.Debug(n.logger).Log("msg", "Telegram message successfully published", "message_id", message.ID, "chat_id", message.Chat.ID)

	return false, nil
}

func createTelegramClient(apiURL, parseMode string, httpClient *http.Client) (*telebot.Bot, error) {
	bot, err := telebot.NewBot(telebot.Settings{
		URL:       apiURL,
		ParseMode: parseMode,
		Client:    httpClient,
		Offline:   true,
	})
	if err != nil {
		return nil, err
	}

	return bot, nil
}

func (n *Notifier) getBotToken() (string, error) {
	if len(n.conf.BotTokenFile) > 0 {
Repository: prometheus/alertmanager
File: provider/mem/mem.go (Go)

Code before:
	r.MustRegister(newMemAlertByStatus(types.AlertStateSuppressed))
	r.MustRegister(newMemAlertByStatus(types.AlertStateUnprocessed))
}

// NewAlerts returns a new alert provider.
func NewAlerts(ctx context.Context, m types.Marker, intervalGC time.Duration, alertCallback AlertStoreCallback, l log.Logger, r prometheus.Registerer) (*Alerts, error) {
	if alertCallback == nil {
		alertCallback = noopCallback{}
	}

	ctx, cancel := context.WithCancel(ctx)
	a := &Alerts{
		marker:    m,
		alerts:    store.NewAlerts(),
		cancel:    cancel,
		listeners: map[int]listeningAlerts{},
		next:      0,
		logger:    log.With(l, "component", "provider"),
		callback:  alertCallback,
	}

	if r != nil {
		a.registerMetrics(r)
	}

	go a.gcLoop(ctx, intervalGC)

	return a, nil
}

func (a *Alerts) gcLoop(ctx context.Context, interval time.Duration) {
	t := time.NewTicker(interval)
	defer t.Stop()
	for {
		select {
		case <-ctx.Done():
			return
		case <-t.C:
			a.gc()
		}
	}
}

func (a *Alerts) gc() {
	a.mtx.Lock()
	defer a.mtx.Unlock()

	deleted := a.alerts.GC()
	for _, alert := range deleted {
		// As we don't persist alerts, we no longer consider them after
		// they are resolved. Alerts waiting for resolved notifications are

Review comment (bug):
I see we stopped using `a.alerts.SetGCCallback` and `a.alerts.Run`, but I don't understand how that helps fix the race condition? Can we not use the mutex at the start of the callback function?

Code after:
	r.MustRegister(newMemAlertByStatus(types.AlertStateSuppressed))
	r.MustRegister(newMemAlertByStatus(types.AlertStateUnprocessed))
}

// NewAlerts returns a new alert provider.
func NewAlerts(ctx context.Context, m types.AlertMarker, intervalGC time.Duration, alertCallback AlertStoreCallback, l log.Logger, r prometheus.Registerer) (*Alerts, error) {
	if alertCallback == nil {
		alertCallback = noopCallback{}
	}

	ctx, cancel := context.WithCancel(ctx)
	a := &Alerts{
		marker:    m,
		alerts:    store.NewAlerts(),
		cancel:    cancel,
		listeners: map[int]listeningAlerts{},
		next:      0,
		logger:    log.With(l, "component", "provider"),
		callback:  alertCallback,
	}

	if r != nil {
		a.registerMetrics(r)
	}

	go a.gcLoop(ctx, intervalGC)

	return a, nil
}

func (a *Alerts) gcLoop(ctx context.Context, interval time.Duration) {
	t := time.NewTicker(interval)
	defer t.Stop()
	for {
		select {
		case <-ctx.Done():
			return
		case <-t.C:
			a.gc()
		}
	}
}

func (a *Alerts) gc() {
	a.mtx.Lock()
	defer a.mtx.Unlock()

	deleted := a.alerts.GC()
	for _, alert := range deleted {
		// As we don't persist alerts, we no longer consider them after
		// they are resolved. Alerts waiting for resolved notifications are
Repository: prometheus/alertmanager
File: provider/mem/mem.go (Go)

Code before:
		done   = make(chan struct{})
		alerts = a.alerts.List()
		ch     = make(chan *types.Alert, max(len(alerts), alertChannelLength))
	)

	for _, a := range alerts {
		ch <- a
	}

	a.listeners[a.next] = listeningAlerts{alerts: ch, done: done}
	a.next++

	return provider.NewAlertIterator(ch, done, nil)
}

// GetPending returns an iterator over all the alerts that have
// pending notifications.
func (a *Alerts) GetPending() provider.AlertIterator {
	var (
		ch   = make(chan *types.Alert, alertChannelLength)
		done = make(chan struct{})
	)

	go func() {
		defer close(ch)
		a.mtx.RLock()
		alerts := a.alerts.List()
		a.mtx.RUnlock()

		for _, a := range alerts {
			select {
			case ch <- a:
			case <-done:
				return
			}
		}
	}()

	return provider.NewAlertIterator(ch, done, nil)
}

// Get returns the alert for a given fingerprint.
func (a *Alerts) Get(fp model.Fingerprint) (*types.Alert, error) {
	a.mtx.RLock()
	defer a.mtx.RUnlock()
	return a.alerts.Get(fp)
}

// Put adds the given alert to the set.
func (a *Alerts) Put(alerts ...*types.Alert) error {
	for _, alert := range alerts {

Review comment (refactor):
What if we move this lock and the `alerts` variable outside the goroutine so we can use `defer` for the unlock?

Code after:
		done   = make(chan struct{})
		alerts = a.alerts.List()
		ch     = make(chan *types.Alert, max(len(alerts), alertChannelLength))
	)

	for _, a := range alerts {
		ch <- a
	}

	a.listeners[a.next] = listeningAlerts{alerts: ch, done: done}
	a.next++

	return provider.NewAlertIterator(ch, done, nil)
}

// GetPending returns an iterator over all the alerts that have
// pending notifications.
func (a *Alerts) GetPending() provider.AlertIterator {
	var (
		ch   = make(chan *types.Alert, alertChannelLength)
		done = make(chan struct{})
	)
	a.mtx.Lock()
	defer a.mtx.Unlock()
	alerts := a.alerts.List()

	go func() {
		defer close(ch)
		for _, a := range alerts {
			select {
			case ch <- a:
			case <-done:
				return
			}
		}
	}()

	return provider.NewAlertIterator(ch, done, nil)
}

// Get returns the alert for a given fingerprint.
func (a *Alerts) Get(fp model.Fingerprint) (*types.Alert, error) {
	a.mtx.Lock()
	defer a.mtx.Unlock()
	return a.alerts.Get(fp)
}

// Put adds the given alert to the set.
func (a *Alerts) Put(alerts ...*types.Alert) error {
	a.mtx.Lock()
	defer a.mtx.Unlock()