Skip to content

Commit 471f026

Browse files
committed
Documentation: Add section about using gen_random_text_uuid as auto-PK
1 parent 7c4a4c9 commit 471f026

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

docs/sqlalchemy.rst

+35
Original file line numberDiff line numberDiff line change
@@ -300,6 +300,41 @@ would translate into the following declarative model:
300300
>>> log.id
301301
...
302302

303+
304+
Auto-generated primary key
305+
..........................
306+
307+
CrateDB 4.5.0 added the :ref:`gen_random_text_uuid() <crate-reference:scalar-gen_random_text_uuid>`
308+
scalar function, which can also be used within an SQL DDL statement, in order to automatically
309+
assign random identifiers to newly inserted records on the server side.
310+
311+
In this spirit, it is suitable to be used as a ``PRIMARY KEY`` constraint for SQLAlchemy.
312+
313+
A table schema like this
314+
315+
.. code-block:: sql
316+
317+
CREATE TABLE "doc"."items" (
318+
"id" STRING DEFAULT gen_random_text_uuid() NOT NULL PRIMARY KEY,
319+
"name" STRING
320+
)
321+
322+
would translate into the following declarative model:
323+
324+
>>> class Item(Base):
325+
...
326+
... __tablename__ = 'items'
327+
...
328+
... id = sa.Column("id", sa.String, server_default=func.gen_random_text_uuid(), primary_key=True)
329+
... name = sa.Column("name", sa.String)
330+
331+
>>> item = Item(name="Foobar")
332+
>>> session.add(item)
333+
>>> session.commit()
334+
>>> item.id
335+
...
336+
337+
303338
.. _using-extension-types:
304339

305340
Extension types

0 commit comments

Comments
 (0)