I am trying to set a default value for an UUID type field
/**
* @var int
*
* @ORM\Column(name="uuid", type="guid", options={"default"="uuid_generate_v4()"})
* @ORM\Id()
* @ORM\GeneratedValue(strategy="UUID")
*/
private $uuid;
However this sets executes
ALTER TABLE store ALTER uuid SET DEFAULT 'uuid_generate_v4()';
and takes it as text. How do I define a DB function as default in doctrine annotations?
On creation table you can use this annotation
/**
* @ORM\Column(name="uuid", type="guid", columnDefinition="DEFAULT uuid_generate_v4()", options={"comment"="Column Comment Here"})
* @ORM\Id()
* @ORM\GeneratedValue(strategy="UUID")
*/
private $uuid;
The ColumnDefinition append the content to DDL see Doctrine Documentation
The SQL output for this config is
ALTER TABLE table_name ADD uuid DEFAULT uuid_generate_v4();
COMMENT ON COLUMN table_name.uuid IS 'Column Comment Here';
These annotation does nothing on CHANGE COLUMN. Only works on ADD COLUMN generated SQL. You must recreate the column or change your table by hand.
IMPORTANT NOTE: For those that looking for create UUID Column Type in PostgreSQL, keep in mind that you need to enable some Extension to use functions that create uuid-hashes.
In the example, uuid_generate_v4() is derived from UUID-OSSP and older versions of PostgreSQL don't support it. Instead UUID-OSSP you can use gen_random_uuid() function from PGCRYPTO . The UUID resultant is the same version (v4). Again, older versions doesn't support it.
Just remember to Install the Extension with Create Extension .
CREATE EXTENSION IF NOT EXISTS "uuid-ossp"; // OR
CREATE EXTENSION IF NOT EXISTS "pgcrypto";
ANOTHER IMPORTANT NOTE: In some PostgreSQL installations (like CentOS), extensions are not included by default. You must install them.
For CentOS/RHEL you need to install postgresql-contrib . Pay attention to the version of your PostgreSQL. Ie for version 9.5 you must use postgresql95-contrib
There's a trick to create uuid hashes without extensions. Just use the instruction above.
uuid_in(md5(random()::text || clock_timestamp()::text)::cstring);
If your version suport ::UUID casting, use
md5(random()::text || clock_timestamp()::text)::uuid
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.