1

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?

Evren Yurtesen
  • 2,267
  • 1
  • 22
  • 40

1 Answers1

3

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. I.e. for version 9.5 you must use postgresql95-contrib

My Privileges are weak

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
Marcos Regis
  • 814
  • 9
  • 13