Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to use composite type as function argument (PostgresQL) #2131

Closed
zmwangx opened this issue Mar 11, 2020 · 2 comments
Closed

How to use composite type as function argument (PostgresQL) #2131

zmwangx opened this issue Mar 11, 2020 · 2 comments

Comments

@zmwangx
Copy link
Contributor

zmwangx commented Mar 11, 2020

PostgresQL supports composite types (e.g. row types) as function arguments, but I can't figure out how to use a model as an argument of a peewee.fn.func.

Say we have this schema

CREATE TABLE IF NOT EXISTS post (
    id INTEGER NOT NULL PRIMARY KEY,
    votes INTEGER NOT NULL,
    posted TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);

and a function

CREATE OR REPLACE FUNCTION score(post)
	RETURNS double precision
	AS $$ SELECT $1.votes / EXTRACT(EPOCH FROM now() - $1.posted); $$
	LANGUAGE SQL
	STABLE;

we want to build this query:

SELECT id, score(post) FROM post;

How do we approach this?

I cannot use the model Post as an argument to peewee.fn.score:

Post.select(Post.id, fn.score(Post))
# => peewee.ProgrammingError: can't adapt type 'ModelBase'

even SQL doesn't work unless I force an alias on the model:

Post.select(Post.id, SQL("score(post)"))
# peewee.ProgrammingError: column "post" does not exist (because 'FROM "post" AS "t1"' in the constructed query)
Post_ = Post.alias("post")
Post_.select(Post_.id, SQL("score(post)"))
# This one works.

I'm currently using the workaround above. Is there any better way to achieve this? Sorry if I missed something in the docs, I think I scoured every corner. (And sorry for the barrage of issues I've opened recently.)

@coleifer
Copy link
Owner

coleifer commented Mar 11, 2020

I believe this is fixed, thanks for the report.

@zmwangx
Copy link
Contributor Author

zmwangx commented Mar 12, 2020

It works now, thanks.

coleifer added a commit that referenced this issue May 19, 2020
Also relocates logic from #2131 to a better place and fixes #2185.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants