File size: 28,759 Bytes
c212805 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 | import PostgrestBuilder from './PostgrestBuilder'
import PostgrestFilterBuilder, { InvalidMethodError } from './PostgrestFilterBuilder'
import { GetResult } from './select-query-parser/result'
import { CheckMatchingArrayTypes } from './types/types'
import { ClientServerOptions, GenericSchema } from './types/common/common'
import type { MaxAffectedEnabled } from './types/feature-flags'
export default class PostgrestTransformBuilder<
ClientOptions extends ClientServerOptions,
Schema extends GenericSchema,
Row extends Record<string, unknown>,
Result,
RelationName = unknown,
Relationships = unknown,
Method = unknown,
ThrowOnError extends boolean = false,
> extends PostgrestBuilder<ClientOptions, Result, ThrowOnError> {
throwOnError(): PostgrestTransformBuilder<
ClientOptions,
Schema,
Row,
Result,
RelationName,
Relationships,
Method,
true
> {
return super.throwOnError() as PostgrestTransformBuilder<
ClientOptions,
Schema,
Row,
Result,
RelationName,
Relationships,
Method,
true
>
}
/**
* Perform a SELECT on the query result.
*
* By default, `.insert()`, `.update()`, `.upsert()`, and `.delete()` do not
* return modified rows. By calling this method, modified rows are returned in
* `data`.
*
* @param columns - The columns to retrieve, separated by commas
*
* @category Database
* @subcategory Using modifiers
*
* @example With `upsert()`
* ```ts
* const { data, error } = await supabase
* .from('characters')
* .upsert({ id: 1, name: 'Han Solo' })
* .select()
* ```
*
* @exampleSql With `upsert()`
* ```sql
* create table
* characters (id int8 primary key, name text);
*
* insert into
* characters (id, name)
* values
* (1, 'Han');
* ```
*
* @exampleResponse With `upsert()`
* ```json
* {
* "data": [
* {
* "id": 1,
* "name": "Han Solo"
* }
* ],
* "status": 201,
* "statusText": "Created"
* }
* ```
*/
select<
Query extends string = '*',
NewResultOne = GetResult<Schema, Row, RelationName, Relationships, Query, ClientOptions>,
>(
columns?: Query
): PostgrestFilterBuilder<
ClientOptions,
Schema,
Row,
Method extends 'RPC'
? Result extends unknown[]
? NewResultOne[]
: NewResultOne
: NewResultOne[],
RelationName,
Relationships,
Method,
ThrowOnError
> {
// Remove whitespaces except when quoted
let quoted = false
const cleanedColumns = (columns ?? '*')
.split('')
.map((c) => {
if (/\s/.test(c) && !quoted) {
return ''
}
if (c === '"') {
quoted = !quoted
}
return c
})
.join('')
this.url.searchParams.set('select', cleanedColumns)
this.headers.append('Prefer', 'return=representation')
return this as unknown as PostgrestFilterBuilder<
ClientOptions,
Schema,
Row,
Method extends 'RPC'
? Result extends unknown[]
? NewResultOne[]
: NewResultOne
: NewResultOne[],
RelationName,
Relationships,
Method,
ThrowOnError
>
}
/**
* Order the query result by `column`.
*
* You can call this method multiple times to order by multiple columns.
*
* You can order referenced tables, but it only affects the ordering of the
* parent table if you use `!inner` in the query.
*
* @param column - The column to order by
* @param options - Named parameters
* @param options.ascending - If `true`, the result will be in ascending order
* @param options.nullsFirst - If `true`, `null`s appear first. If `false`,
* `null`s appear last.
* @param options.referencedTable - Set this to order a referenced table by
* its columns
*
* @category Database
* @subcategory Using modifiers
*/
order<ColumnName extends string & keyof Row>(
column: ColumnName,
options?: { ascending?: boolean; nullsFirst?: boolean; referencedTable?: undefined }
): this
order(
column: string,
options?: { ascending?: boolean; nullsFirst?: boolean; referencedTable?: string }
): this
/**
* @deprecated Use `options.referencedTable` instead of `options.foreignTable`
*/
order<ColumnName extends string & keyof Row>(
column: ColumnName,
options?: { ascending?: boolean; nullsFirst?: boolean; foreignTable?: undefined }
): this
/**
* @deprecated Use `options.referencedTable` instead of `options.foreignTable`
*/
order(
column: string,
options?: { ascending?: boolean; nullsFirst?: boolean; foreignTable?: string }
): this
/**
* Order the query result by `column`.
*
* You can call this method multiple times to order by multiple columns.
*
* You can order referenced tables, but it only affects the ordering of the
* parent table if you use `!inner` in the query.
*
* @param column - The column to order by
* @param options - Named parameters
* @param options.ascending - If `true`, the result will be in ascending order
* @param options.nullsFirst - If `true`, `null`s appear first. If `false`,
* `null`s appear last.
* @param options.referencedTable - Set this to order a referenced table by
* its columns
* @param options.foreignTable - Deprecated, use `options.referencedTable`
* instead
*
* @category Database
* @subcategory Using modifiers
*
* @example With `select()`
* ```ts
* const { data, error } = await supabase
* .from('characters')
* .select('id, name')
* .order('id', { ascending: false })
* ```
*
* @exampleSql With `select()`
* ```sql
* create table
* characters (id int8 primary key, name text);
*
* insert into
* characters (id, name)
* values
* (1, 'Luke'),
* (2, 'Leia'),
* (3, 'Han');
* ```
*
* @exampleResponse With `select()`
* ```json
* {
* "data": [
* {
* "id": 3,
* "name": "Han"
* },
* {
* "id": 2,
* "name": "Leia"
* },
* {
* "id": 1,
* "name": "Luke"
* }
* ],
* "status": 200,
* "statusText": "OK"
* }
* ```
*
* @exampleDescription On a referenced table
* Ordering with `referencedTable` doesn't affect the ordering of the
* parent table.
*
* @example On a referenced table
* ```ts
* const { data, error } = await supabase
* .from('orchestral_sections')
* .select(`
* name,
* instruments (
* name
* )
* `)
* .order('name', { referencedTable: 'instruments', ascending: false })
*
* ```
*
* @exampleSql On a referenced table
* ```sql
* create table
* orchestral_sections (id int8 primary key, name text);
* create table
* instruments (
* id int8 primary key,
* section_id int8 not null references orchestral_sections,
* name text
* );
*
* insert into
* orchestral_sections (id, name)
* values
* (1, 'strings'),
* (2, 'woodwinds');
* insert into
* instruments (id, section_id, name)
* values
* (1, 1, 'harp'),
* (2, 1, 'violin');
* ```
*
* @exampleResponse On a referenced table
* ```json
* {
* "data": [
* {
* "name": "strings",
* "instruments": [
* {
* "name": "violin"
* },
* {
* "name": "harp"
* }
* ]
* },
* {
* "name": "woodwinds",
* "instruments": []
* }
* ],
* "status": 200,
* "statusText": "OK"
* }
* ```
*
* @exampleDescription Order parent table by a referenced table
* Ordering with `referenced_table(col)` affects the ordering of the
* parent table.
*
* @example Order parent table by a referenced table
* ```ts
* const { data, error } = await supabase
* .from('instruments')
* .select(`
* name,
* section:orchestral_sections (
* name
* )
* `)
* .order('section(name)', { ascending: true })
*
* ```
*
* @exampleSql Order parent table by a referenced table
* ```sql
* create table
* orchestral_sections (id int8 primary key, name text);
* create table
* instruments (
* id int8 primary key,
* section_id int8 not null references orchestral_sections,
* name text
* );
*
* insert into
* orchestral_sections (id, name)
* values
* (1, 'strings'),
* (2, 'woodwinds');
* insert into
* instruments (id, section_id, name)
* values
* (1, 2, 'flute'),
* (2, 1, 'violin');
* ```
*
* @exampleResponse Order parent table by a referenced table
* ```json
* {
* "data": [
* {
* "name": "violin",
* "orchestral_sections": {"name": "strings"}
* },
* {
* "name": "flute",
* "orchestral_sections": {"name": "woodwinds"}
* }
* ],
* "status": 200,
* "statusText": "OK"
* }
* ```
*/
order(
column: string,
{
ascending = true,
nullsFirst,
foreignTable,
referencedTable = foreignTable,
}: {
ascending?: boolean
nullsFirst?: boolean
foreignTable?: string
referencedTable?: string
} = {}
): this {
const key = referencedTable ? `${referencedTable}.order` : 'order'
const existingOrder = this.url.searchParams.get(key)
this.url.searchParams.set(
key,
`${existingOrder ? `${existingOrder},` : ''}${column}.${ascending ? 'asc' : 'desc'}${
nullsFirst === undefined ? '' : nullsFirst ? '.nullsfirst' : '.nullslast'
}`
)
return this
}
/**
* Limit the query result by `rows`.
*
* @param rows - The maximum number of rows to return
* @param options - Named parameters
* @param options.referencedTable - Set this to limit rows of referenced
* tables instead of the parent table
* @param options.foreignTable - Deprecated, use `options.referencedTable`
* instead
*
* @category Database
* @subcategory Using modifiers
*
* @example With `select()`
* ```ts
* const { data, error } = await supabase
* .from('characters')
* .select('name')
* .limit(1)
* ```
*
* @exampleSql With `select()`
* ```sql
* create table
* characters (id int8 primary key, name text);
*
* insert into
* characters (id, name)
* values
* (1, 'Luke'),
* (2, 'Leia'),
* (3, 'Han');
* ```
*
* @exampleResponse With `select()`
* ```json
* {
* "data": [
* {
* "name": "Luke"
* }
* ],
* "status": 200,
* "statusText": "OK"
* }
* ```
*
* @example On a referenced table
* ```ts
* const { data, error } = await supabase
* .from('orchestral_sections')
* .select(`
* name,
* instruments (
* name
* )
* `)
* .limit(1, { referencedTable: 'instruments' })
* ```
*
* @exampleSql On a referenced table
* ```sql
* create table
* orchestral_sections (id int8 primary key, name text);
* create table
* instruments (
* id int8 primary key,
* section_id int8 not null references orchestral_sections,
* name text
* );
*
* insert into
* orchestral_sections (id, name)
* values
* (1, 'strings');
* insert into
* instruments (id, section_id, name)
* values
* (1, 1, 'harp'),
* (2, 1, 'violin');
* ```
*
* @exampleResponse On a referenced table
* ```json
* {
* "data": [
* {
* "name": "strings",
* "instruments": [
* {
* "name": "violin"
* }
* ]
* }
* ],
* "status": 200,
* "statusText": "OK"
* }
* ```
*/
limit(
rows: number,
{
foreignTable,
referencedTable = foreignTable,
}: { foreignTable?: string; referencedTable?: string } = {}
): this {
const key = typeof referencedTable === 'undefined' ? 'limit' : `${referencedTable}.limit`
this.url.searchParams.set(key, `${rows}`)
return this
}
/**
* Limit the query result by starting at an offset `from` and ending at the offset `to`.
* Only records within this range are returned.
* This respects the query order and if there is no order clause the range could behave unexpectedly.
* The `from` and `to` values are 0-based and inclusive: `range(1, 3)` will include the second, third
* and fourth rows of the query.
*
* @param from - The starting index from which to limit the result
* @param to - The last index to which to limit the result
* @param options - Named parameters
* @param options.referencedTable - Set this to limit rows of referenced
* tables instead of the parent table
* @param options.foreignTable - Deprecated, use `options.referencedTable`
* instead
*
* @category Database
* @subcategory Using modifiers
*
* @example With `select()`
* ```ts
* const { data, error } = await supabase
* .from('characters')
* .select('name')
* .range(0, 1)
* ```
*
* @exampleSql With `select()`
* ```sql
* create table
* characters (id int8 primary key, name text);
*
* insert into
* characters (id, name)
* values
* (1, 'Luke'),
* (2, 'Leia'),
* (3, 'Han');
* ```
*
* @exampleResponse With `select()`
* ```json
* {
* "data": [
* {
* "name": "Luke"
* },
* {
* "name": "Leia"
* }
* ],
* "status": 200,
* "statusText": "OK"
* }
* ```
*/
range(
from: number,
to: number,
{
foreignTable,
referencedTable = foreignTable,
}: { foreignTable?: string; referencedTable?: string } = {}
): this {
const keyOffset =
typeof referencedTable === 'undefined' ? 'offset' : `${referencedTable}.offset`
const keyLimit = typeof referencedTable === 'undefined' ? 'limit' : `${referencedTable}.limit`
this.url.searchParams.set(keyOffset, `${from}`)
// Range is inclusive, so add 1
this.url.searchParams.set(keyLimit, `${to - from + 1}`)
return this
}
/**
* Set the AbortSignal for the fetch request.
*
* @param signal - The AbortSignal to use for the fetch request
*
* @category Database
* @subcategory Using modifiers
*
* @remarks
* You can use this to set a timeout for the request.
*
* @exampleDescription Aborting requests in-flight
* You can use an [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) to abort requests.
* Note that `status` and `statusText` don't mean anything for aborted requests as the request wasn't fulfilled.
*
* @example Aborting requests in-flight
* ```ts
* const ac = new AbortController()
*
* const { data, error } = await supabase
* .from('very_big_table')
* .select()
* .abortSignal(ac.signal)
*
* // Abort the request after 100 ms
* setTimeout(() => ac.abort(), 100)
* ```
*
* @exampleResponse Aborting requests in-flight
* ```json
* {
* "error": {
* "message": "AbortError: The user aborted a request.",
* "details": "",
* "hint": "The request was aborted locally via the provided AbortSignal.",
* "code": ""
* },
* "status": 0,
* "statusText": ""
* }
*
* ```
*
* @example Set a timeout
* ```ts
* const { data, error } = await supabase
* .from('very_big_table')
* .select()
* .abortSignal(AbortSignal.timeout(1000 /* ms *\/))
* ```
*
* @exampleResponse Set a timeout
* ```json
* {
* "error": {
* "message": "FetchError: The user aborted a request.",
* "details": "",
* "hint": "",
* "code": ""
* },
* "status": 400,
* "statusText": "Bad Request"
* }
*
* ```
*/
abortSignal(signal: AbortSignal): this {
this.signal = signal
return this
}
/**
* Return `data` as a single object instead of an array of objects.
*
* Query result must be one row (e.g. using `.limit(1)`), otherwise this
* returns an error.
*
* @category Database
* @subcategory Using modifiers
*
* @example With `select()`
* ```ts
* const { data, error } = await supabase
* .from('characters')
* .select('name')
* .limit(1)
* .single()
* ```
*
* @exampleSql With `select()`
* ```sql
* create table
* characters (id int8 primary key, name text);
*
* insert into
* characters (id, name)
* values
* (1, 'Luke'),
* (2, 'Leia'),
* (3, 'Han');
* ```
*
* @exampleResponse With `select()`
* ```json
* {
* "data": {
* "name": "Luke"
* },
* "status": 200,
* "statusText": "OK"
* }
* ```
*/
single<ResultOne = Result extends (infer ResultOne)[] ? ResultOne : never>(): PostgrestBuilder<
ClientOptions,
ResultOne,
ThrowOnError
> {
this.headers.set('Accept', 'application/vnd.pgrst.object+json')
return this as unknown as PostgrestBuilder<ClientOptions, ResultOne, ThrowOnError>
}
/**
* Return `data` as a single object instead of an array of objects.
*
* Query result must be zero or one row (e.g. using `.limit(1)`), otherwise
* this returns an error.
*
* @category Database
* @subcategory Using modifiers
*
* @example With `select()`
* ```ts
* const { data, error } = await supabase
* .from('characters')
* .select()
* .eq('name', 'Katniss')
* .maybeSingle()
* ```
*
* @exampleSql With `select()`
* ```sql
* create table
* characters (id int8 primary key, name text);
*
* insert into
* characters (id, name)
* values
* (1, 'Luke'),
* (2, 'Leia'),
* (3, 'Han');
* ```
*
* @exampleResponse With `select()`
* ```json
* {
* "status": 200,
* "statusText": "OK"
* }
* ```
*/
maybeSingle<
ResultOne = Result extends (infer ResultOne)[] ? ResultOne : never,
>(): PostgrestBuilder<ClientOptions, ResultOne | null, ThrowOnError> {
// No Accept header override — we fetch as a list and enforce cardinality client-side.
// Fixes https://github.com/supabase/postgrest-js/issues/361 for all request methods.
this.isMaybeSingle = true
return this as unknown as PostgrestBuilder<ClientOptions, ResultOne | null, ThrowOnError>
}
/**
* Return `data` as a string in CSV format.
*
* @category Database
* @subcategory Using modifiers
*
* @exampleDescription Return data as CSV
* By default, the data is returned in JSON format, but can also be returned as Comma Separated Values.
*
* @example Return data as CSV
* ```ts
* const { data, error } = await supabase
* .from('characters')
* .select()
* .csv()
* ```
*
* @exampleSql Return data as CSV
* ```sql
* create table
* characters (id int8 primary key, name text);
*
* insert into
* characters (id, name)
* values
* (1, 'Luke'),
* (2, 'Leia'),
* (3, 'Han');
* ```
*
* @exampleResponse Return data as CSV
* ```json
* {
* "data": "id,name\n1,Luke\n2,Leia\n3,Han",
* "status": 200,
* "statusText": "OK"
* }
* ```
*/
csv(): PostgrestBuilder<ClientOptions, string, ThrowOnError> {
this.headers.set('Accept', 'text/csv')
return this as unknown as PostgrestBuilder<ClientOptions, string, ThrowOnError>
}
/**
* Return `data` as an object in [GeoJSON](https://geojson.org) format.
*
* @category Database
* @subcategory Using modifiers
*/
geojson(): PostgrestBuilder<ClientOptions, Record<string, unknown>, ThrowOnError> {
this.headers.set('Accept', 'application/geo+json')
return this as unknown as PostgrestBuilder<ClientOptions, Record<string, unknown>, ThrowOnError>
}
/**
* Return `data` as the EXPLAIN plan for the query.
*
* You need to enable the
* [db_plan_enabled](https://supabase.com/docs/guides/database/debugging-performance#enabling-explain)
* setting before using this method.
*
* @param options - Named parameters
*
* @param options.analyze - If `true`, the query will be executed and the
* actual run time will be returned
*
* @param options.verbose - If `true`, the query identifier will be returned
* and `data` will include the output columns of the query
*
* @param options.settings - If `true`, include information on configuration
* parameters that affect query planning
*
* @param options.buffers - If `true`, include information on buffer usage
*
* @param options.wal - If `true`, include information on WAL record generation
*
* @param options.format - The format of the output, can be `"text"` (default)
* or `"json"`
*
* @category Database
* @subcategory Using modifiers
*
* @exampleDescription Get the execution plan
* By default, the data is returned in TEXT format, but can also be returned as JSON by using the `format` parameter.
*
* @example Get the execution plan
* ```ts
* const { data, error } = await supabase
* .from('characters')
* .select()
* .explain()
* ```
*
* @exampleSql Get the execution plan
* ```sql
* create table
* characters (id int8 primary key, name text);
*
* insert into
* characters (id, name)
* values
* (1, 'Luke'),
* (2, 'Leia'),
* (3, 'Han');
* ```
*
* @exampleResponse Get the execution plan
* ```js
* Aggregate (cost=33.34..33.36 rows=1 width=112)
* -> Limit (cost=0.00..18.33 rows=1000 width=40)
* -> Seq Scan on characters (cost=0.00..22.00 rows=1200 width=40)
* ```
*
* @exampleDescription Get the execution plan with analyze and verbose
* By default, the data is returned in TEXT format, but can also be returned as JSON by using the `format` parameter.
*
* @example Get the execution plan with analyze and verbose
* ```ts
* const { data, error } = await supabase
* .from('characters')
* .select()
* .explain({analyze:true,verbose:true})
* ```
*
* @exampleSql Get the execution plan with analyze and verbose
* ```sql
* create table
* characters (id int8 primary key, name text);
*
* insert into
* characters (id, name)
* values
* (1, 'Luke'),
* (2, 'Leia'),
* (3, 'Han');
* ```
*
* @exampleResponse Get the execution plan with analyze and verbose
* ```js
* Aggregate (cost=33.34..33.36 rows=1 width=112) (actual time=0.041..0.041 rows=1 loops=1)
* Output: NULL::bigint, count(ROW(characters.id, characters.name)), COALESCE(json_agg(ROW(characters.id, characters.name)), '[]'::json), NULLIF(current_setting('response.headers'::text, true), ''::text), NULLIF(current_setting('response.status'::text, true), ''::text)
* -> Limit (cost=0.00..18.33 rows=1000 width=40) (actual time=0.005..0.006 rows=3 loops=1)
* Output: characters.id, characters.name
* -> Seq Scan on public.characters (cost=0.00..22.00 rows=1200 width=40) (actual time=0.004..0.005 rows=3 loops=1)
* Output: characters.id, characters.name
* Query Identifier: -4730654291623321173
* Planning Time: 0.407 ms
* Execution Time: 0.119 ms
* ```
*/
explain({
analyze = false,
verbose = false,
settings = false,
buffers = false,
wal = false,
format = 'text',
}: {
analyze?: boolean
verbose?: boolean
settings?: boolean
buffers?: boolean
wal?: boolean
format?: 'json' | 'text'
} = {}) {
const options = [
analyze ? 'analyze' : null,
verbose ? 'verbose' : null,
settings ? 'settings' : null,
buffers ? 'buffers' : null,
wal ? 'wal' : null,
]
.filter(Boolean)
.join('|')
// An Accept header can carry multiple media types but postgrest-js always sends one
const forMediatype = this.headers.get('Accept') ?? 'application/json'
this.headers.set(
'Accept',
`application/vnd.pgrst.plan+${format}; for="${forMediatype}"; options=${options};`
)
if (format === 'json') {
return this as unknown as PostgrestBuilder<
ClientOptions,
Record<string, unknown>[],
ThrowOnError
>
} else {
return this as unknown as PostgrestBuilder<ClientOptions, string, ThrowOnError>
}
}
/**
* Dry-run this request: execute the query but discard the changes.
*
* Server-side, PostgREST runs the query inside a transaction and rolls it back
* instead of committing. The response still contains the data that *would* have
* been returned — `RETURNING` clauses execute and RLS, triggers, and constraints
* are all evaluated — but no row is actually inserted, updated, or deleted.
*
* This affects only the single request it is chained to. The JS caller has no
* handle on the transaction: supabase-js does not group multiple queries into
* one transaction. For multi-statement transactional logic, use a database
* function (`supabase.rpc(...)`).
*
* Sets the `Prefer: tx=rollback` header. See PostgREST's docs on transaction
* preferences for the underlying mechanism.
*
* @category Database
* @subcategory Using modifiers
*
* @example Validate an insert without persisting
* ```ts
* const { data, error } = await supabase
* .from('countries')
* .insert({ name: 'France' })
* .select()
* .rollback()
* // `data` shows what would have been inserted; nothing is saved.
* ```
*/
rollback(): this {
this.headers.append('Prefer', 'tx=rollback')
return this
}
/**
* Override the type of the returned `data`.
*
* @typeParam NewResult - The new result type to override with
* @deprecated Use overrideTypes<yourType, { merge: false }>() method at the end of your call chain instead
*
* @category Database
* @subcategory Using modifiers
*
* @remarks
* - Deprecated: use overrideTypes method instead
*
* @example Override type of successful response
* ```ts
* const { data } = await supabase
* .from('countries')
* .select()
* .returns<Array<MyType>>()
* ```
*
* @exampleResponse Override type of successful response
* ```js
* let x: typeof data // MyType[]
* ```
*
* @example Override type of object response
* ```ts
* const { data } = await supabase
* .from('countries')
* .select()
* .maybeSingle()
* .returns<MyType>()
* ```
*
* @exampleResponse Override type of object response
* ```js
* let x: typeof data // MyType | null
* ```
*/
returns<NewResult>(): PostgrestTransformBuilder<
ClientOptions,
Schema,
Row,
CheckMatchingArrayTypes<Result, NewResult>,
RelationName,
Relationships,
Method,
ThrowOnError
> {
return this as unknown as PostgrestTransformBuilder<
ClientOptions,
Schema,
Row,
CheckMatchingArrayTypes<Result, NewResult>,
RelationName,
Relationships,
Method,
ThrowOnError
>
}
/**
* Set the maximum number of rows that can be affected by the query.
* Only available in PostgREST v13+ and only works with PATCH and DELETE methods.
*
* @param rows - The maximum number of rows that can be affected
*
* @category Database
* @subcategory Using modifiers
*/
maxAffected(rows: number): MaxAffectedEnabled<ClientOptions['PostgrestVersion']> extends true
? // TODO: update the RPC case to only work on RPC that returns SETOF rows
Method extends 'PATCH' | 'DELETE' | 'RPC'
? this
: InvalidMethodError<'maxAffected method only available on update or delete'>
: InvalidMethodError<'maxAffected method only available on postgrest 13+'> {
this.headers.append('Prefer', 'handling=strict')
this.headers.append('Prefer', `max-affected=${rows}`)
return this as unknown as MaxAffectedEnabled<ClientOptions['PostgrestVersion']> extends true
? Method extends 'PATCH' | 'DELETE' | 'RPC'
? this
: InvalidMethodError<'maxAffected method only available on update or delete'>
: InvalidMethodError<'maxAffected method only available on postgrest 13+'>
}
}
|