Insert UUID to PostgreSQL table using PDO - postgresql

I am using UUID's in PostgreSQL as Primary Key for my tables. I am trying to insert the UUID using PDO and prepared statement. However, I am not able to bind the value using bindValue. These are the steps I am trying to follow:
$sql = "INSERT INTO customers.customers(customer_id, first_name, last_name, email_address)";
$sql .= " VALUES(":customer_id", ":first_name", ":last_name", ":email_address")";
$this->stmt = prepare($sql);
$this->stmt = bindValue(":customer_id", $customer_uuid); //*** WHAT PDO value to use Here??????
$this->stmt = bindValue(":first_name", $first_name, PDO::PARAM_STR);
$this->stmt = bindValue(":last_name", $last_name, PDO::PARAM_STR);
$this->stmt = bindValue(":email_address", "$email_address, PDO::PARAM_STR);
$this->stmt->execute();
As can be seen here, each "bindValue" statement required to have a PDO parameter type value. I have not been able to find what value can be used for a UUID type column. I tried using the PDO::PARAM_STR, but this creates a Data Type error when inserting the UUID int he column as the column type for customer_id is UUID.
Any suggestions from the community here?
I tried converting the UUID to string and then back to UUID, but it did not work. From here, I don't know what else I can try.

Related

Use UUID in Doobie SQL update

I have the following simple (cut down for brevity) Postgres table:
create table users(
id uuid NOT NULL,
year_of_birth smallint NOT NULL
);
Within a test I have seeded data.
When I run the following SQL update to correct a year_of_birth the error implies that I'm not providing the necessary UUID correctly.
The Doobie SQL I run is:
val id: String = "6ee7a37c-6f58-4c14-a66c-c17083adff81"
val correctYear: Int = 1980
sql"update users set year_of_birth = $correctYear where id = $id".update.run
I have tried both with and without quotes around the given $id e.g. the other version is:
sql"update users set year_of_birth = $correctYear where id = '$id'".update.run
The error upon running the above is:
org.postgresql.util.PSQLException: ERROR: operator does not exist: uuid = character varying
Hint: No operator matches the given name and argument type(s). You might need to add explicit type casts.
Both comments provided viable solutions.
a_horse_with_no_name suggested the use of cast which works though the SQL becomes no so nice when compared to the other solution.
AminMal suggested the use of available Doobie implicits which can handle a UUID within SQL and thus avoid a cast.
So I changed my code to the following:
import doobie.postgres.implicits._
val id: UUID = UUID.fromString("6ee7a37c-6f58-4c14-a66c-c17083adff81")
sql"update users set year_of_birth = $correctYear where id = $id".update.run
So I'd like to mark this question as resolved because of the comment provided by AminMal

I am having trouble with my postgresql query

I have a query in mysql works well, but when I go to postgresql does not update me, I want to know where is my error.
I leave my php file the query update does not work
<?php
require_once "Controllers/conexion.php";
session_start();
$resultado=pg_query("SELECT nextval('user_id_seq') as key");
$row=pg_fetch_array($resultado, 0);
$key=$row['key'];
try {
$resultado = pg_query($conexion,"select * from encuesta_respuesta where id_user = '".$_SESSION['user']."' and id_encuesta = '".$_POST['id_encuesta']."'");
while( $row = pg_fetch_assoc($resultado)){
$data = $row;
}
if ($data['estado']=='F') {
header("Location: Inicio.php");
}
foreach($_POST['pregunta'] as $id_pregunta=>$valor){
$query="insert into encuesta_respuesta_opcion values (".$key.",".$_POST['id_encuesta'].",".$id_pregunta.",".$valor.")";
$resultado = pg_query($conexion,$query);
}
$query="update encuesta_respuesta set estado='F' where id_user=".$_SESSION['user']." and id_encuesta = ".$_POST['id_encuesta'];
$resultado = pg_query($conexion,$query);
$resp['error']=false;
} catch (Exception $e) {
$resp['error']=true;
}
header("Location: Inicio.php");
?>
Directly try to update data in your database, check this query works or not. If it works, then you have to change your query building procedure in your application. For example:
postgres=# create table test (id_user VARCHAR (50) PRIMARY KEY, id_encuesta VARCHAR (50), estado VARCHAR (10));
postgres=# insert into test values ('anower','engg.','A');
postgres=# update test set estado='F' where id_user='anower' and id_encuesta='engg.';
The query should work the same in MySql and postgres.
If you are getting different results during updates then your survey tables arent the same.
Most liked id_user and id_encuesta are autoincrement fields. So they dont necesary have the same values.
Try using a Select to see if they have same survey information.
SELECT *
FROM survey
where id_user=".$_SESSION['user']."
and id_encuesta = ".$_POST['id_encuesta'];

postgres return last id codeigniter

I'm new with postgres database codeigniter
for return last id in mysql
im using this in my model
public function daftar($data){
$this->db->insert('akun', $data);
return $this->db->insert_id();
}
but I'm confuse how to return las id ($this->db->insert_id) in postgres?
From the CodeIgniter documentation:
If using the PDO driver with PostgreSQL, or using the Interbase driver, this function requires a $name parameter, which specifies the appropriate sequence to check for the insert id.
In your case you need return $this->db->insert_id('akun_id_akun_seq'); if "akun_id_akun_seq" is the name of the respective sequence.
If your INSERT is something like this:
INSERT INTO public."MyTable"
(
"SomethingIdFk",
"Date"
)
VALUES
(
8,
CURRENT_TIMESTAMP
);
And MyTable has a serial like MyTableId as primary key, then in your model you can do this:
$id= $this->db->insert_id('public."MyTable_MyTableId_seq"');
to get the last insert id.
That works for me.
More info you can find in this post.

Default value doesn't work in SQLAlchemy + PostgreSQL + aiopg + psycopg2

I've found an unexpected behavior in SQLAlchemy. I'm using the following versions:
SQLAlchemy (0.9.8)
PostgreSQL (9.3.5)
psycopg2 (2.5.4)
aiopg (0.5.1)
This is the table definition for the example:
import asyncio
from aiopg.sa import create_engine
from sqlalchemy import (
MetaData,
Column,
Integer,
Table,
String,
)
metadata = MetaData()
users = Table('users', metadata,
Column('id_user', Integer, primary_key=True, nullable=False),
Column('name', String(20), unique=True),
Column('age', Integer, nullable=False, default=0),
)
Now if I try to execute a simple insert to the table just populating the id_user and name, the column age should be auto-generated right? Lets see...
#asyncio.coroutine
def go():
engine = yield from create_engine('postgresql://USER#localhost/DB')
data = {'id_user':1, 'name':'Jimmy' }
stmt = users.insert(values=data, inline=False)
with (yield from engine) as conn:
result = yield from conn.execute(stmt)
loop = asyncio.get_event_loop()
loop.run_until_complete(go())
This is the resulting statement with the corresponding error:
INSERT INTO users (id_user, name, age) VALUES (1, 'Jimmy', null);
psycopg2.IntegrityError: null value in column "age" violates not-null constraint
I didn't provide the age column, so where is that age = null value coming from? I was expecting something like this:
INSERT INTO users (id_user, name) VALUES (1, 'Jimmy');
Or if the default flag actually works should be:
INSERT INTO users (id_user, name, Age) VALUES (1, 'Jimmy', 0);
Could you put some light on this?
This issue has been confirmed has an aiopg bug. Seems like at the moment it's ignoring the default argument on data manipulation.
I've fixed the issue using server_default instead:
users = Table('users', metadata,
Column('id_user', Integer, primary_key=True, nullable=False),
Column('name', String(20), unique=True),
Column('age', Integer, nullable=False, server_default='0'))
I think you need to use inline=True in your insert. This turns off 'pre-execution'.
Docs are a bit cryptic on what exactly this 'pre-execution' entails, but they mentions default parameters:
:param inline:
if True, SQL defaults present on :class:`.Column` objects via
the ``default`` keyword will be compiled 'inline' into the statement
and not pre-executed. This means that their values will not
be available in the dictionary returned from
:meth:`.ResultProxy.last_updated_params`.
This piece of docstring is from Update class, but they have a shared behavior with Insert.
Besides, that's the only way they test it:
https://github.com/zzzeek/sqlalchemy/blob/rel_0_9/test/sql/test_insert.py#L385

querying MS Access column properties with OleDb

I'm using OLE and C#.NET to query the schema of a MS Access database. Specifically, I need to find out whether a particular column is an "identity" column or not. For SQL Server, I can use:
select COLUMNPROPERTY(object_id('dbo.tablename'),'columnname','IsIdentity')
... but when I invoke this SQL against Access, I get an OleDbException with the following message:
Undefined function 'COLUMNPROPERTY' in expression.
Searching the archives, it appears there are ways to do this with DAO, but I need to use OLE. Anyone happen to know how I can do this with OLE?
You can get the schema from the connection, for example:
cn.GetOleDbSchemaTable(OleDbSchemaGuid.Indexes,
new Object[] { null, null, null, null, "Table1" });
Is the indexes for Table1. One of the fields returned is PRIMARY_KEY
See http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbschemaguid.columns(v=vs.71)
The same using the GetSchema method.
using(OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=C:\temp\db.mdb;" +
"Persist Security Info=False;"))
{
con.Open();
var schema = con.GetSchema("Indexes");
var col = schema.Select("TABLE_NAME = 'YourTableName' AND PRIMARY_KEY = True");
Console.WriteLine(col[0]["COLUMN_NAME"].ToString());
}