You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/_fragments/_js-default-caution.mdx
+2-2
Original file line number
Diff line number
Diff line change
@@ -1,7 +1,7 @@
1
1
:::caution
2
2
3
-
The generation of values for `DataTypes.UUIDV1` and `DataTypes.UUIDV4`, `DataTypes.NOW` and other JavaScript functions are not handled by the Database,
4
-
but by Sequelize itself. This means that they will only be used when using Model methods. They will not be used in [raw queries](../querying/raw-queries.md),
3
+
The generation of values for `DataTypes.NOW` and other JavaScript functions are not handled by the Database,
4
+
but by Sequelize itself. This means that they will only be used when using Model methods. They will not be used in [raw queries](../querying/raw-queries.mdx),
5
5
in [migrations](../models/migrations.md), and all other places where Sequelize does not have access to the Model.
6
6
7
7
Read about SQL based alternatives in [Dynamic SQL default values](../models/defining-models.mdx#dynamic-sql-default-values).
Sequelize provides [a lot of built-in data types](pathname:///api/v7/modules/_sequelize_core.index.DataTypes.html). To access a built-in data type, you must import `DataTypes`:
11
12
@@ -212,6 +213,9 @@ MyModel.init({
212
213
213
214
For UUIDs, use `DataTypes.UUID`. It becomes the `UUID` data type for PostgreSQL and SQLite, and `CHAR(36)` for MySQL.
214
215
216
+
You can also use `DataTypes.UUID.V4` and `DataTypes.UUID.V1`
217
+
to limit which version of UUID is accepted by the attribute to v4 or v1 respectively.
@@ -222,18 +226,36 @@ For UUIDs, use `DataTypes.UUID`. It becomes the `UUID` data type for PostgreSQL
222
226
223
227
### Built-in Default Values for UUID
224
228
225
-
Sequelize can generate UUIDs automatically for these attributes, simply use `DataTypes.UUIDV1` or `DataTypes.UUIDV4` as the default value:
229
+
Sequelize can generate UUIDs automatically for these attributes, simply use [`sql.uuidV1` or `sql.uuidV4`](../querying/raw-queries.mdx#sqluuidv4--sqluuidv1) as the default value:
226
230
227
231
```javascript
228
232
MyModel.init({
229
233
myUuid: {
230
-
type:DataTypes.UUID,
231
-
defaultValue:DataTypes.UUIDV4, // Or DataTypes.UUIDV1
234
+
type:DataTypes.UUID.V4,
235
+
defaultValue:sql.uuidV4, // Or sql.uuidV1
232
236
},
233
237
});
234
238
```
235
239
236
-
<JsDefaultCaution />
240
+
In supported dialects, Sequelize will set the default value to the appropriate function, as shown in the table below.
241
+
These dialects can also use these two functions in migrations.
242
+
243
+
In all other dialects, Sequelize will generate the UUID value itself, in JavaScript.
244
+
This means that they cannot use these two functions in migrations.
245
+
246
+
<UuidSupportTable />
247
+
248
+
The postgres dialect requires the `uuid-ossp` extension to be enabled to be able to generate v1 UUIDs.
249
+
If this extension is not available, you can force Sequelize to generate the UUIDs itself by using `sql.uuidV1.asJavaScript` instead.
Copy file name to clipboardExpand all lines: docs/models/defining-models.mdx
+26-26
Original file line number
Diff line number
Diff line change
@@ -235,13 +235,9 @@ class User extends Model {
235
235
236
236
### Dynamic JS default values
237
237
238
-
Instead of a static value, you can also use a JavaScript function that sequelize will call every time a new instance is created. Sequelize provides 3 built-in functions that you can use, but a custom function can be used as well:
239
-
240
-
-[`DataTypes.NOW`](./data-types.mdx#built-in-default-values-for-dates) for the current timestamp
241
-
-[`DataTypes.UUIDV4`](./data-types.mdx#built-in-default-values-for-uuid) for a UUIDv4
242
-
-[`DataTypes.UUIDV1`](./data-types.mdx#built-in-default-values-for-uuid) for a UUIDv1
243
-
244
-
<JsDefaultCaution />
238
+
Instead of a static value, you can also use a JavaScript function that sequelize will call every time a new instance is created.
239
+
Sequelize provides the built-in [`DataTypes.NOW`](./data-types.mdx#built-in-default-values-for-dates) for the current timestamp,
240
+
but a custom function can be used as well:
245
241
246
242
<TabsgroupId="ts-js">
247
243
<TabItemvalue="ts"label="TypeScript">
@@ -296,28 +292,27 @@ class User extends Model {
296
292
</TabItem>
297
293
</Tabs>
298
294
295
+
<JsDefaultCaution />
296
+
299
297
### Dynamic SQL default values
300
298
301
-
You can also use a SQL function as a default value using either [`fn`] or [`literal`].
302
-
This has the advantage over [dynamic JS default values](#dynamic-js-default-values) that the function will always be called, since it is handled by the database, not by Sequelize.
299
+
You can also use a SQL function as a default value using [raw SQL](../querying/raw-queries.mdx).
300
+
This has the advantage over [dynamic JS default values](#dynamic-js-default-values) that the function will always be called,
301
+
since it is handled by the database, not by Sequelize.
303
302
304
-
For instance, if your dialect provides a built-in SQL function to generate UUIDs, you can use [`fn`]to set a default value on the SQL layer:
303
+
For instance, you could use the [`sql.fn`](../querying/raw-queries.mdx#sqlfn) function to make the database generate a random number for you:
// 'uuid_generate_v4' is only available in postgres + uuid-ossp
335
-
// other dialects may support this function under different names.
336
-
// highlight-next-line
337
-
@Default(sql.fn('uuid_generate_v4'))
338
-
id;
327
+
@Attribute(DataTypes.FLOAT)
328
+
@Default(sql.fn('random'))
329
+
randomNumber;
339
330
}
340
331
```
341
332
342
333
</TabItem>
343
334
</Tabs>
344
335
336
+
Sequelize also provides 2 built-in functions, [`sql.uuidV1` and `sql.uuidV4`](./data-types.mdx#built-in-default-values-for-uuid), that will
337
+
generate a UUID in SQL if possible, and fallback to a JavaScript implementation otherwise.
338
+
339
+
:::info
340
+
341
+
In MySQL, it is only possible to use dynamic SQL default values starting with version [8.0.13](https://dev.mysql.com/doc/relnotes/mysql/8.0/en/news-8-0-13.html).
342
+
343
+
:::
344
+
345
345
## Primary Keys
346
346
347
347
Sequelize automatically adds an auto-incremented integer attribute called `id` as primary key if none is specified.
Copy file name to clipboardExpand all lines: docs/other-topics/extending-data-types.md
+3-3
Original file line number
Diff line number
Diff line change
@@ -102,8 +102,8 @@ export class MyDateType extends DataTypes.ABSTRACT<Date> {
102
102
We also have 4 methods that can be implemented to define how the Data Type serializes & deserializes values when interacting with the database:
103
103
104
104
-`parseDatabaseValue(value): unknown`: Transforms values retrieved from the database[^caveat-1].
105
-
-`toBindableValue(value): unknown`: Transforms a value into a value accepted by the connector library when using [bind parameters](../querying/raw-queries.md#bind-parameters).
106
-
-`escape(value): string`: Escapes a value for inlining inside of raw SQL, such as when using [replacements](../querying/raw-queries.md#replacements).
105
+
-`toBindableValue(value): unknown`: Transforms a value into a value accepted by the connector library when using [bind parameters](../querying/raw-queries.mdx#bind-parameters).
106
+
-`escape(value): string`: Escapes a value for inlining inside of raw SQL, such as when using [replacements](../querying/raw-queries.mdx#replacements).
107
107
By default, if `toBindableValue` returns a string, this method will escape that string as a SQL string.
108
108
109
109
```typescript
@@ -171,4 +171,4 @@ When using `DataTypes.ENUM`, Sequelize will automatically create the enum type i
171
171
If you need to create a custom type, you will need to create it manually in the database before you can use it in one of your models.
172
172
173
173
[^caveat-1]: `parseDatabaseValue` is only called if a Sequelize Data Type is specified in the query.
174
-
This is the case when using model methods, but not when using [raw queries](../querying/raw-queries.md) or when not specifying the model in [`QueryInterface`](pathname:///api/v7/classes/_sequelize_core.index.AbstractQueryInterface.html) methods
174
+
This is the case when using model methods, but not when using [raw queries](../querying/raw-queries.mdx) or when not specifying the model in [`QueryInterface`](pathname:///api/v7/classes/_sequelize_core.index.AbstractQueryInterface.html) methods
@@ -262,7 +262,7 @@ These include but are not limited to:
262
262
263
263
- Instances being deleted by the database because of an `ON DELETE CASCADE` constraint, [except if the `hooks` option is true](#hooks-for-cascade-deletes).
264
264
- Instances being updated by the database because of a `SET NULL` or `SET DEFAULT` constraint.
265
-
-[Raw queries](../querying/raw-queries.md).
265
+
-[Raw queries](../querying/raw-queries.mdx).
266
266
- All QueryInterface methods.
267
267
268
268
If you need to react to these events, consider using your database's native and notification system instead.
If we had not included the transaction option in our call to `User.update` in the preceding code,
355
-
no change would have occurred, since our newly created user does not exist in the database until the pending transaction
354
+
If we had not included the transaction option in our call to `User.update` in the preceding code,
355
+
no change would have occurred, since our newly created user does not exist in the database until the pending transaction
356
356
has been committed.
357
357
358
358
[^find-all]: **findAll**: Note that some methods, such as `Model.findOne`, `Model.findAndCountAll` and association getters will also call `Model.findAll` internally. This will cause the `beforeFind` hook to be called for these methods too.
We believe that ORMs are inherently leaky abstractions. They are a compromise between the flexibility of SQL and the convenience of an object-oriented programming language.
7
9
As such, it does not make sense to try to provide a 100% complete abstraction over SQL (which could easily be more difficult to read than the SQL itself).
8
10
@@ -97,7 +99,7 @@ whereas bind parameters are sent to the database separately from the SQL query t
97
99
98
100
A query can have both bind parameters and replacements.
99
101
100
-
Each database uses a different syntax for bind parameters, but Sequelize provides its own unification layer.
102
+
Each database uses a different syntax for bind parameters, but Sequelize provides its own unification layer.
101
103
102
104
Inconsequentially to which database you use, in Sequelize bind parameters are written following a postgres-like syntax. You can either:
103
105
@@ -201,7 +203,7 @@ $$;
201
203
);
202
204
```
203
205
204
-
The above query looks like code, has syntax coloring that makes it look like code, but is really a regular dollar-quoted string
206
+
The above query looks like code, has syntax coloring that makes it look like code, but is really a regular dollar-quoted string
205
207
that will be interpreted as SQL by the `DO` clause (similarly to `eval` in JavaScript).
206
208
207
209
Dollar-quoted strings end as soon as `$$` is encountered. If the user passes `$$` as the `id` parameter, the query will end early and will
@@ -359,7 +361,7 @@ SELECT * FROM "projects" WHERE '2012-01-01' BETWEEN "createdAt" AND "publishedAt
359
361
360
362
### `sql.attribute`
361
363
362
-
The `sql.attribute` function can be used to reference the name of a Model attribute. It is similar to the [`sql.identifier`](#sqlidentifier) function,
364
+
The `sql.attribute` function can be used to reference the name of a Model attribute. It is similar to the [`sql.identifier`](#sqlidentifier) function,
363
365
but the name of the attribute will be mapped to the name of the column, whereas `sql.identifier` escapes its value as-is:
364
366
365
367
```ts
@@ -483,11 +485,29 @@ Attributes support a shorthand syntax for casting. See [Casting syntax in `sql.a
483
485
484
486
:::
485
487
488
+
### `sql.uuidV4` & `sql.uuidV1`
489
+
490
+
In supported dialects, using `sql.uuidV4` and `sql.uuidV1` will generate the dialect-specific function to generate a UUID.
491
+
In unsupported dialects, using these functions, except as [the default value of an attribute](../models/data-types.mdx#built-in-default-values-for-uuid), will throw an error.
492
+
493
+
```ts
494
+
sequelize.query(sql`INSERT INTO users (id) VALUES (${sql.uuidV4()})`);
495
+
```
496
+
497
+
```sql
498
+
-- postgres example
499
+
INSERT INTO users (id) VALUES (gen_random_uuid())
500
+
```
501
+
502
+
These functions are supported by the following dialects:
503
+
504
+
<UuidSupportTable />
505
+
486
506
### `sql.col`
487
507
488
508
:::caution
489
509
490
-
This function is available for backwards compatibility, and there are currently no plans to deprecate it,
510
+
This function is available for backwards compatibility, and there are currently no plans to deprecate it,
491
511
but it is not recommended to use in new code. Prefer instead to use [`sql.attribute`](#sqlattribute), [`sql.identifier`](#sqlidentifier),
0 commit comments