postgresql db functions are not working - php

I was trying to get the nearest people from mover_location table using the query as follows :
select * from mover_location where
public.st_dwithin(public.st_geogfromtext('SRID=4326;POINT(11.2565999 75.7711587)'),
last_seen_location_geog, 1060)
Which is not working and give me error like as follows :
ERROR: function _st_expand(public.geography, double precision) does not exist
and i didnt called the st_expand function , How can i resolve this ,Or is there any other
workarounds ? thanks .
My mover_location table structure is as follows ,here last_seen_location_geog is of geography type
UPDATE :-
HINT: No function matches the given name and argument types. You might need to add explicit type casts.
QUERY: SELECT $1 && _ST_Expand($2,$3) AND $2 && _ST_Expand($1,$3) AND _ST_DWithin($1, $2, $3, true)
CONTEXT: SQL function "st_dwithin" during inlining

Add public schema to your search_path:
set search_path to your_schema, public;

Related

No function matches the given name and argument types, what does it mean. Project is working fine locally, but throwing this error on heroku

SQLSTATE[42883]: Undefined function: 7 ERROR: function sum(character varying) does not exist
LINE 1: select sum("amount") as aggregate from "payments"
^
HINT: No function matches the given name and argument types. You might need to add explicit type casts. (SQL: select sum("amount") as aggregate from "payments")
PDOException
SQLSTATE[42883]: Undefined function: 7 ERROR: function sum(character varying) does not exist LINE 1: select sum("amount") as aggregate from "payments" ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts.
It's a Laravel Project and working fine locally, but throwing this error on Heroku, please kindly assist.
This is my code: $totalAmount = DB::table('payments')->sum('amount');
Its working fine locally.
For others facing this same issue.
Firstly, sum() does not accept varchar or string( if your column data type is varchar/string you will get that error ).
You can change your data type to integer or double( or the likes ).
Write you code like this $totalAmount = Payment::select(DB::raw('sum(cast(amount as double))'))->get(); ( remember get() will return and array )
or $totalAmount = DB::raw('SUM(amount)'); instead of $totalAmount = DB::table('payments')->sum('amount'); ( but you can write it like this if you will go for the first option to change data type)
For me I changed data type to integer and use this $totalAmount = DB::table('payments')->sum('amount');

Undefined table: 7 ERROR: relation "V5TableName" does not exist

I am using an MVC framework (Zend) for my application and I want to find the total size of a table in PostgreSQL (including index). The table name is "V5TableName" - quotes included because table name is case sensitive. I have made sure that there is NO typo involved.
My code to get the table size is shown below:
public function getMyTableSize()
{
$sql = "SELECT pg_size_pretty(pg_total_relation_size( '\"V5TableName\"' ) );";
/* Custom_Db is a custom library in my application which makes the PostgreSQL connection
and queries the database
*/
$tableSize = Custom_Db::query($sql)->fetchColumn();
return $tableSize;
}
When my application calls this function it returns the following error in my logs :
[22-Apr-2020 09:42:37] PID:30849 ERR: SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "V5TableName" does not exist
LINE 1: SELECT pg_size_pretty(pg_total_relation_size( '"V5TableName...
^
query was: SELECT pg_size_pretty(pg_total_relation_size( '"V5TableName"' ) );
If I run this same query in pgAdmin4 it works perfectly fine returning the table size (for instance: 104Mb).
I have tried:
Removing and adding quotes to the table name in the code.
Appending the schema as prefix to the table name (example: 'public."V5TableName"').
NONE of the above seem to work. I am not sure what is going wrong over here.
I also tried to find the total database size in my application (db name: MyDbName - with mixed case spelling) and my query looked something like below:
$sql = "SELECT pg_size_pretty(pg_database_size('MyDbName'))"; // this DID NOT WORK
So I changed it to the one shown below: (it worked)
$sql = "SELECT pg_size_pretty(pg_database_size( current_database() ))"; // this WORKED
I was wondering if there is something similar that could be done to find the table size.
Your query should work. The use of double-quotes seems correct.
SELECT pg_size_pretty(pg_total_relation_size('"V5TableName"'));
First make sure you are connecting to the right database cluster (a.k.a. "server"). It's defined by its data directory, or equally unambiguous by hostname and port number. Read the manual here and here.
Then make sure you are connecting to the right database within that database cluster. A Postgres database cluster consists of 1-n databases. When connecting without specifying the actual database, you end up in the maintenance database named postgres by default. That's the most likely explanation. Check with:
SELECT current_database();
Then check for the right table and schema name:
SELECT * FROM pg_tables
WHERE tablename ~* 'V5TableName'; -- ~* matches case-insensitive
The first riddle should be solved at this point.
Check your DB spelling and possible near-duplicates with:
SELECT datname FROM pg_database;
The call is without double-quotes (like you tried correctly), but requires correct capitalization:
SELECT pg_size_pretty(pg_database_size('MyDbName'));
Note the subtle difference (as documented in the manual):
pg_database_size() takes oid or name. So pass the case-sensitive database name without double-quotes.
pg_total_relation_size() takes regclass. So pass the case-sensitive relation name with double-quotes if you need to preserve capitalization.
pg_database_size() has to differ because there is no dedicated object identifier type for databases (no regdatabase).
The gist of it: avoid double-quoted identifiers in Postgres if at all possible. It makes your life easier.

Laravel groupBy Database query Builder not working

I have this problem in a query using laravel groupBy, it simply return a groupBy error. I have read the documentation about this but can't really figure it out. I also read the same problem pointing that it is because of postgreSQL that I need to include all the columns in grouBy clause. I tried it but still it doesn't return the distinct values. Please help me with this. Below is my code. Thanks a lot.
Controller function
public function index(){
$purchases = Purchase::groupBy('purchase_order_id')->get();
return view('purchases/purchases_crud', ['allPurchases' => $purchases]);
}
Table to query
Error
QueryException in Connection.php line 680:
SQLSTATE[42803]: Grouping error: 7 ERROR: column "purchases.id" must appear
in the GROUP BY clause or be used in an aggregate function
LINE 1: select * from "purchases" group by "purchase_order_id"
^ (SQL: select * from "purchases" group by "purchase_order_id")
There you have it add group by "purchases.id" or restrict the select to only the operates that are needed.
->select("purchase_order_id","purchases.id")
->groupBy("purchases.id") // add if possible
Agreggates for your case should mean something like ->select("sum(po_total)")
If we group by id, we get all results as id is unique, my mistake. You want something like this
DB::table("purchases")->select("purchase_order_id", DB:raw("sum(po_total)"))->groupBy("purchase_order_id")->g‌​et();
Rule of thumb is you either select a field with Sum() or have it on the group by

Postgresql custom function returning table

I am using PostgreSQL 9.1.11.
I need to return result of SELECT to my php script. The invocation in php is like this:
$res = $pdb->getAssoc("SELECT * FROM my_profile();");
The class code to illustrate what is going on in php
public function getAssoc($in_query) {
$res = pg_query($this->_Link, $in_query);
if($res == FALSE) {
return array("dberror", iconv("utf-8", "windows-1251", pg_last_error($this->_Link)));
}
return pg_fetch_all($res);
}
Next comes my function in Postgres. I fully re-create database by dropping in a script when I update any function. (The project is in the early stage of development.) I have little to no experience doing stored procedures.
I get this error:
structure of query does not match function result type
CONTEXT: PL/pgSQL function "my_profile" line 3 at RETURN QUERY )
Trying to write:
CREATE FUNCTION my_profile()
RETURNS TABLE (_nick text, _email text) AS $$
BEGIN
RETURN QUERY SELECT (nick, email) FROM my_users WHERE id = 1;
END;
$$
LANGUAGE 'plpgsql' SECURITY DEFINER;
Table structure is:
CREATE TABLE my_users(
id integer NOT NULL,
nick text,
email text,
pwd_salt varchar(32),
pwd_hash character(128),
CONSTRAINT users_pk PRIMARY KEY (id)
);
When I return 1 column in a table the query works. Tried to rewrite procedure in LANGUAGE sql instead of plpgsql with some success, but I want to stick to plpgsql.
The Postgres 9.1.11, php-fpm I am using is latest for fully updated amd64 Debian wheezy.
What I want to do is to return a recordset containing from 0 to n rows from proc to php in an associative array.
This part is incorrect:
RETURN QUERY SELECT (nick, email) FROM my_users WHERE id = 1;
You should remove the parentheses around nick,email otherwise they form a unique column with a ROW type.
This is why it doesn't match the result type.
#Daniel already pointed out your immediate problem (incorrect use of parentheses). But there is more:
Never quote the language name plpgsql in this context. It's an identifier, not a string literal. It's tolerated for now since it's a wide-spread anti-pattern. But it may be considered a syntax error in future releases.
The SECURITY DEFINER clause should be accompanied by a local setting for search_path. Be sure to read the according chapter in the manual.
Everything put together, it could look like this:
CREATE FUNCTION my_profile()
RETURNS TABLE (nick text, email text) AS
$func$
BEGIN
RETURN QUERY
SELECT m.nick, m.email FROM my_users m WHERE m.id = 1;
END
$func$
LANGUAGE plpgsql SECURITY DEFINER SET search_path = public, pg_temp;
Replace public whit the actual schema of your table.
To avoid possible naming conflicts between OUT parameters in RETURNS TABLE ... and table columns in the SELECT statement I table-qualified column names with the given alias m.

How to pass custom type array to Postgres function

I have a custom type
CREATE TYPE mytype as (id uuid, amount numeric(13,4));
I want to pass it to a function with the following signature:
CREATE FUNCTION myschema.myfunction(id uuid, mytypes mytype[])
RETURNS BOOLEAN AS...
How can I call this in postgres query and inevitably from PHP?
You can use the alternative syntax with a array literal instead of the array constructor, which is a Postgres function-like construct and may cause trouble when you need to pass values - like in a prepared statement:
SELECT myschema.myfunc('0d6311cc-0d74-4a32-8cf9-87835651e1ee'
, '{"(0d6311cc-0d74-4a32-8cf9-87835651e1ee, 25)"
, "(6449fb3b-844e-440e-8973-31eb6bbefc81, 10)"}'::mytype[]);
I added a line break between the two row types in the array for display. That's legal.
How to find the correct syntax for any literal?
Just ask Postgres. Here is a demo:
CREATE TABLE mytype (id uuid, amount numeric(13,4));
INSERT INTO mytype VALUES
('0d6311cc-0d74-4a32-8cf9-87835651e1ee', 25)
,('6449fb3b-844e-440e-8973-31eb6bbefc81', 10);
SELECT ARRAY(SELECT m FROM mytype m);
Returns:
{"(0d6311cc-0d74-4a32-8cf9-87835651e1ee,25.0000)","(6449fb3b-844e-440e-8973-31eb6bbefc81,10.0000)"}
db<>fiddle here
Any table (including temporary tables) implicitly creates a row type of the same name.
select myschema.myfunc('0d6311cc-0d74-4a32-8cf9-87835651e1ee'
, ARRAY[('ac747f0e-93d4-43a9-bc5b-09df06593239', '25.00')
, ('6449fb3b-844e-440e-8973-31eb6bbefc81', '10.00')]::mytype[]
);
Still need PHP portion of this resolved though, still not sure how to call a function populating with the custom array parameter.

Categories