Skip to content

Add scalar row factory #723

@embecka

Description

@embecka

Please, add scalar_row factory to return a scalar value instead of a tuple.

Usage:

with connection.cursor(row_factory=scalar_row()) as cursor:
	cursor.execute("SELECT username FROM user WHERE id = %(id)s", {"id": 1})
	
	print(cursor.fetchone())  # Prints "username" instead of ("username",)

Possible implementation:

def scalar_row(index: int = 0) -> BaseRowFactory[Any]:
	def scalar_row_(cursor: BaseCursor[Any, Any]) -> RowMaker[Any]:
		res = cursor.pgresult
		if not res:
			return no_result
		
		nfields = _get_nfields(res)
		if nfields is None:
			return no_result
		
		if index >= nfields:
			return no_result
		
		def scalar_row__(values: Sequence[Any]) -> Any:
			return values[index]
		
		return scalar_row__
	
	return scalar_row_

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions