Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
519615d5fb | ||
|
|
de5a8954b2 | ||
|
|
64b5a59410 | ||
|
|
417a96d137 | ||
|
|
53593824a8 | ||
|
|
e642086d27 | ||
|
|
e451700d5d | ||
|
|
13868983af | ||
|
|
db9da0b1ca | ||
|
|
f09655b7a6 | ||
|
|
8715e426c0 | ||
|
|
9a40bc266e | ||
|
|
e67461b991 | ||
|
|
420933ceba | ||
|
|
8f8dbd3425 | ||
|
|
8d7d7e4112 | ||
|
|
521acf61cb | ||
|
|
d3f7cba92e | ||
|
|
a71d9ea50f | ||
|
|
5a1e9b01e4 | ||
|
|
d3292d42de | ||
|
|
572581cbb6 | ||
|
|
9daddb549c | ||
|
|
716fcbf147 | ||
|
|
5b62501ce7 | ||
|
|
7860e7287f | ||
|
|
c958f94753 | ||
|
|
94f0548344 | ||
|
|
16d0e1ca8c | ||
|
|
9657d46c42 | ||
|
|
70e07ccbc6 | ||
|
|
cc5c4ae5ef | ||
|
|
af8b62ba10 | ||
|
|
d4e7d23268 | ||
|
|
4e084b664c | ||
|
|
91024b6eab | ||
|
|
0e4fcd7387 | ||
|
|
49a7aa9933 | ||
|
|
ec89f6b90c | ||
|
|
82aa58a08f | ||
|
|
db85faf3ed | ||
|
|
a2d00e305a | ||
|
|
4beac10d3d | ||
|
|
70a8a80491 | ||
|
|
b4d235f72a | ||
|
|
1a8b6972a8 | ||
|
|
aaf2d2e430 | ||
|
|
a46bea16e2 | ||
|
|
50b2d302d0 | ||
|
|
82a43c2767 | ||
|
|
a51a74b3c1 | ||
|
|
1c371d7340 | ||
|
|
30ca64d849 | ||
|
|
9c165e3edb | ||
|
|
c8612f1df1 | ||
|
|
da9e497ef1 | ||
|
|
47e9a2d134 | ||
|
|
4e0ffa6d0a | ||
|
|
f5767b8d86 | ||
|
|
8cbcf9867b | ||
|
|
a1582a6136 | ||
|
|
1ca5b6f6ba | ||
|
|
aea563bd82 | ||
|
|
5d3d09923f | ||
|
|
71711bb935 | ||
|
|
ad5bb38d70 | ||
|
|
89eae607f5 | ||
|
|
dcfc6673b7 | ||
|
|
7671d63f06 | ||
|
|
04d6f41f45 | ||
|
|
5cc32c7f87 | ||
|
|
11c9e8dac9 | ||
|
|
b8436fd397 | ||
|
|
4156070838 | ||
|
|
9e6a89ffb8 | ||
|
|
d08e5959a0 | ||
|
|
279febe26b | ||
|
|
c4b0bd347b | ||
|
|
7e61c9deb0 | ||
|
|
3cf565614d | ||
|
|
bfa4e1bedb | ||
|
|
d5a4c5609e | ||
|
|
80783a7ee8 | ||
|
|
c8ba505b99 | ||
|
|
ae91fd89b3 | ||
|
|
756aad7827 | ||
|
|
aa75412932 | ||
|
|
ea4d1596b7 | ||
|
|
33b6ba8199 | ||
|
|
9d763aef00 | ||
|
|
d25df459ea | ||
|
|
05447bae33 | ||
|
|
f6b2aa5a5d | ||
|
|
923a271105 | ||
|
|
b8fe512def | ||
|
|
271b3b273d | ||
|
|
5c040e74f5 | ||
|
|
4a3fdc175c | ||
|
|
aef29d49ba | ||
|
|
c6f152f5b4 | ||
|
|
7a5079542c | ||
|
|
71885bdba6 | ||
|
|
8392357863 | ||
|
|
334c2710f6 | ||
|
|
07222cff7b | ||
|
|
575dd4cf70 | ||
|
|
d03b321659 | ||
|
|
5580fe0040 | ||
|
|
7d713b8c53 | ||
|
|
2cb45bd5f8 | ||
|
|
3026c1f308 | ||
|
|
1fa35cb3b8 | ||
|
|
01a56db7d8 | ||
|
|
577a7c7598 | ||
|
|
c4295b3d63 | ||
|
|
aa94e436fa | ||
|
|
cf7a789e9e | ||
|
|
a7ed5db78a | ||
|
|
d903a8a115 | ||
|
|
a427fb67f6 | ||
|
|
3afa5f6a36 | ||
|
|
fdcadb3d53 | ||
|
|
747c78f6f4 | ||
|
|
e96e16fa27 | ||
|
|
0060abeb01 | ||
|
|
f9e9740999 | ||
|
|
1b584f7e9c | ||
|
|
1374178f27 | ||
|
|
cb6151eb1b | ||
|
|
b006016d07 | ||
|
|
df9b373465 | ||
|
|
b34c00c522 | ||
|
|
1d4f31514f | ||
|
|
7e91e5311d | ||
|
|
21bc48ad9a | ||
|
|
cabe744f01 | ||
|
|
463dfb552d | ||
|
|
a57d12b102 | ||
|
|
d9ba9a8208 | ||
|
|
8433f9812b | ||
|
|
c67f1c398c | ||
|
|
2f98d837ff | ||
|
|
eec35d4569 | ||
|
|
9fe90bf9a8 | ||
|
|
58d8133454 | ||
|
|
fe0f2f708a | ||
|
|
dd8d51ab71 | ||
|
|
cdcab34852 | ||
|
|
1ca2d1f8be | ||
|
|
5aa62d944d | ||
|
|
5c29742d7f | ||
|
|
cc7165ca10 | ||
|
|
277342bf8c | ||
|
|
d9a51f23ce | ||
|
|
cdb877135b | ||
|
|
7e5fd317e6 | ||
|
|
40bd9a7769 | ||
|
|
5e41121551 | ||
|
|
46d8dfde42 | ||
|
|
85a4e35a2d | ||
|
|
359a14533b | ||
|
|
69bbce5b32 | ||
|
|
3eff4670f0 | ||
|
|
357400b2b8 | ||
|
|
653c7955b2 | ||
|
|
29cd7d195c | ||
|
|
e788776ec3 | ||
|
|
3e615bd0d9 | ||
|
|
bddfa2782d | ||
|
|
6858693291 | ||
|
|
dcb9f92b80 | ||
|
|
6a38cc098d | ||
|
|
81ceac8ba3 | ||
|
|
88abf600c4 | ||
|
|
80f83f0366 | ||
|
|
b6a50ab8ed | ||
|
|
87a463f857 | ||
|
|
ed407350ad | ||
|
|
de788c9832 | ||
|
|
07dc37e66f | ||
|
|
c2994fb0b1 | ||
|
|
6863fe1e26 | ||
|
|
dc6399abad | ||
|
|
0d13b842a6 | ||
|
|
1bf0c54dd6 | ||
|
|
9d1dc783bf | ||
|
|
69c6ce9c38 | ||
|
|
c57ec52229 | ||
|
|
973201a8d3 | ||
|
|
fbc4d565ca | ||
|
|
2de32fc108 | ||
|
|
460259548d | ||
|
|
b88191299f | ||
|
|
4bcd6725fe | ||
|
|
70396d3f6c | ||
|
|
c9136816a2 | ||
|
|
4428253efe | ||
|
|
47a4e2bfd0 | ||
|
|
5880e62d7a | ||
|
|
2772b78013 | ||
|
|
b91908b749 | ||
|
|
ab73624366 | ||
|
|
5ab317caa0 | ||
|
|
a66738b892 | ||
|
|
3d55f77bae | ||
|
|
d7c64a93f8 | ||
|
|
2543b8d724 | ||
|
|
6de3ba543d | ||
|
|
06ff56d323 | ||
|
|
c33ca4e60c | ||
|
|
b75cc853b4 | ||
|
|
745e7868b0 | ||
|
|
378c11104b | ||
|
|
428a6fef63 | ||
|
|
d02540ac44 | ||
|
|
3f162535b8 | ||
|
|
a5bb20bbf8 | ||
|
|
f1f01f1f5c | ||
|
|
ee359192fa | ||
|
|
941ea0f929 | ||
|
|
ee8b3ef8fe | ||
|
|
47b70b8329 | ||
|
|
727ef465c1 | ||
|
|
210cded560 | ||
|
|
11d8da046c | ||
|
|
4b289b1c97 | ||
|
|
92ac7e574e | ||
|
|
ec7ab271d6 | ||
|
|
4a2c851ae5 | ||
|
|
86e15dbb77 | ||
|
|
00f5780415 | ||
|
|
650249ed29 | ||
|
|
9405a62de8 | ||
|
|
05cdbb34c2 | ||
|
|
8eb88ef218 | ||
|
|
cf7b9bad08 | ||
|
|
c276e9741e | ||
|
|
6a2677d985 | ||
|
|
58999f5102 | ||
|
|
2f91853cb1 | ||
|
|
b8b957667b | ||
|
|
db56c3eecc | ||
|
|
d5cb6b57ea | ||
|
|
f72b47c485 | ||
|
|
0eda5df644 | ||
|
|
d3f15baa4a | ||
|
|
29ffb9329b | ||
|
|
a1480c758e | ||
|
|
2479e0d4a5 | ||
|
|
4878719b90 | ||
|
|
629ace0103 | ||
|
|
73199127bb | ||
|
|
a090f28cea | ||
|
|
c7eb4036a1 | ||
|
|
08901323a3 | ||
|
|
1db6c04a28 | ||
|
|
e70f001cfc | ||
|
|
3b497a5db4 | ||
|
|
5bf0b9ca14 | ||
|
|
e5aee49891 | ||
|
|
873ac6221e | ||
|
|
f97c6e3db3 | ||
|
|
d6153be67a | ||
|
|
e6cde92f11 | ||
|
|
f7879bd4b1 | ||
|
|
11accb760a | ||
|
|
44e041282c | ||
|
|
f2483dc722 | ||
|
|
c18ccf5232 | ||
|
|
79e172a65c | ||
|
|
b49e3b1e5b | ||
|
|
6caaee777b | ||
|
|
86b2e59f6f | ||
|
|
0738785d72 | ||
|
|
2c2513b9cd | ||
|
|
9314dede2d | ||
|
|
ccc386cf38 | ||
|
|
caf0a70171 | ||
|
|
22e8906c40 | ||
|
|
0b3f6de015 | ||
|
|
c59736b902 | ||
|
|
19423b0c0a | ||
|
|
e9abb64fc0 | ||
|
|
57ef98a316 | ||
|
|
31a3864f85 | ||
|
|
073280ad32 | ||
|
|
333f8cf592 | ||
|
|
f9fdf666ad | ||
|
|
c54e0d3353 | ||
|
|
3a3601cbeb | ||
|
|
1a141c19df | ||
|
|
b8f35d880f | ||
|
|
791b86cbf6 | ||
|
|
944b02fbb8 | ||
|
|
95b8751496 | ||
|
|
9b1ff2235a | ||
|
|
7c6c056e92 | ||
|
|
229bc77886 | ||
|
|
8a21a9c34e | ||
|
|
6d506df6f3 | ||
|
|
32e1900370 | ||
|
|
fac7acafa3 | ||
|
|
645217333b | ||
|
|
fcd29caecf | ||
|
|
553ac79d9b | ||
|
|
b2ad914435 | ||
|
|
8ee4e9f0bb | ||
|
|
8f2b6b1652 | ||
|
|
b1deb049c8 | ||
|
|
51db5ce26f | ||
|
|
e7dde2806c | ||
|
|
4325a4f9d5 | ||
|
|
77715dcabf | ||
|
|
aaaf0572ce | ||
|
|
500aad3360 | ||
|
|
3d95c41115 | ||
|
|
6eaaa9aa9b | ||
|
|
f33bccbcdb | ||
|
|
6c886b1291 | ||
|
|
0e7af7b77b | ||
|
|
4a796e0758 | ||
|
|
8ff9f3292e | ||
|
|
5804b754e3 | ||
|
|
16bc853114 | ||
|
|
272c1cc1e2 | ||
|
|
72de95b069 | ||
|
|
c196d406d4 | ||
|
|
b435f1b2d4 | ||
|
|
3750f35e3f | ||
|
|
c2a333efc4 | ||
|
|
a1f2ecadda | ||
|
|
e110fdbd2c | ||
|
|
75a86ba873 | ||
|
|
b2dda6a5d3 | ||
|
|
9a145f6931 | ||
|
|
311a38193b | ||
|
|
4954859d68 | ||
|
|
a7afcc4de9 | ||
|
|
1b855d805e | ||
|
|
4059e1ea76 | ||
|
|
93e50b1d90 | ||
|
|
2ae96e7733 | ||
|
|
9167ae9462 | ||
|
|
3664343989 | ||
|
|
18d105f8c2 | ||
|
|
c004840e76 | ||
|
|
00fbe9ff3e | ||
|
|
2466f4e738 | ||
|
|
3432f75ed4 | ||
|
|
b22bb748f2 | ||
|
|
21e8ca5051 | ||
|
|
410fa9508b | ||
|
|
dcfdd8dfc9 | ||
|
|
ca777315b0 | ||
|
|
f513a71c7a | ||
|
|
09c5cbece5 | ||
|
|
073320133d | ||
|
|
f17f23bd9f | ||
|
|
fd1efa4635 | ||
|
|
db16683ba2 | ||
|
|
8a3b0c60ad | ||
|
|
5424be76d9 | ||
|
|
066fa8b6aa | ||
|
|
f9ee1f7e73 | ||
|
|
4a0b93c451 | ||
|
|
49584728b6 | ||
|
|
868913d179 | ||
|
|
74d8ddec36 | ||
|
|
ea02729ebd | ||
|
|
9fe0f50709 | ||
|
|
1c02e1e3a0 | ||
|
|
7d096e5de5 | ||
|
|
0eca2954b3 | ||
|
|
cc9b725005 | ||
|
|
4a1b9a4609 | ||
|
|
f51090f3d1 | ||
|
|
71887e4b78 | ||
|
|
a45058ba02 | ||
|
|
310d04065e | ||
|
|
63ff6d1f15 | ||
|
|
45cabacdcc | ||
|
|
bbc0bda6f5 | ||
|
|
c1b46ffa1b | ||
|
|
439db880dd | ||
|
|
43f552dbab | ||
|
|
c43696c9a6 | ||
|
|
411cf430ad | ||
|
|
071a3d436f | ||
|
|
c94aa9ccd9 | ||
|
|
dcb6c5bb13 | ||
|
|
85fbb233a7 | ||
|
|
259d97acee | ||
|
|
3a639c7172 | ||
|
|
d75be243ac | ||
|
|
2ffb97991d | ||
|
|
2e298824d6 | ||
|
|
76b1c00935 | ||
|
|
d7246b4851 | ||
|
|
286103daf2 | ||
|
|
9c78751871 | ||
|
|
820917bcb6 | ||
|
|
02312804f0 | ||
|
|
7a387c7a30 | ||
|
|
6682baebd2 | ||
|
|
e4c60889ee | ||
|
|
c070cb9502 | ||
|
|
a8165a89a0 | ||
|
|
9ef0e677e0 | ||
|
|
cb5d80aff8 | ||
|
|
be2778edb5 | ||
|
|
0e7d507e5e | ||
|
|
74a3217bee | ||
|
|
e063a29212 | ||
|
|
f5fca59b2e | ||
|
|
740fcdf5ab | ||
|
|
f864437055 | ||
|
|
4bb98225d8 | ||
|
|
fdaeea8fd2 | ||
|
|
6c3d7a946d | ||
|
|
c29d876f90 | ||
|
|
1e4efafd9e | ||
|
|
50ac91d1ae | ||
|
|
f73845159c | ||
|
|
0ce37f8fd6 | ||
|
|
b2095a8ef6 | ||
|
|
d99e3ac805 | ||
|
|
3af63cb94c | ||
|
|
1680a6eed3 | ||
|
|
c97bd1f01b | ||
|
|
9e04bd7da6 | ||
|
|
0b77098460 | ||
|
|
3ec6526467 | ||
|
|
4a1dee453b | ||
|
|
93bdae962e | ||
|
|
6a34018cfc | ||
|
|
2aa5373a27 | ||
|
|
f95a8e77a6 | ||
|
|
a59cfafe10 | ||
|
|
6b9fde59cd | ||
|
|
1e65a72264 | ||
|
|
4fb521cac6 | ||
|
|
cf258ef499 | ||
|
|
0938e72c5c | ||
|
|
e31363a325 | ||
|
|
5bd7cda308 | ||
|
|
cbfff2804d | ||
|
|
41ea4e6db6 | ||
|
|
f9294c5e43 | ||
|
|
d24a3c82ef | ||
|
|
c6b71551f4 | ||
|
|
d49e3d7132 | ||
|
|
f80a33cf32 | ||
|
|
8fd4fa0d09 | ||
|
|
72083361bc | ||
|
|
48dee75d1a | ||
|
|
92573215b9 | ||
|
|
6277eb43f7 | ||
|
|
b04a7f0080 | ||
|
|
0c65bf494d | ||
|
|
70c0d88fa7 | ||
|
|
2b4e0cc10a | ||
|
|
1268b0a258 | ||
|
|
11f40c384a | ||
|
|
2bb9cee996 | ||
|
|
a38eee399e | ||
|
|
ee4321623f | ||
|
|
49903ca6db | ||
|
|
d15e357d2e | ||
|
|
62512268cd | ||
|
|
84152b483a | ||
|
|
9fe11249f9 | ||
|
|
7640de34e2 | ||
|
|
31ce39ba36 | ||
|
|
ca5eb64deb | ||
|
|
a72241ad4e | ||
|
|
b080f59bac | ||
|
|
558e9d40e8 | ||
|
|
958339b8d3 | ||
|
|
3d56f8435d | ||
|
|
e620ae5e9c | ||
|
|
bd6d8624ab | ||
|
|
03e384d55b | ||
|
|
dfa875c8c7 | ||
|
|
33891e3a73 | ||
|
|
8483459d59 | ||
|
|
7b5c2f03fc | ||
|
|
b538ab9823 | ||
|
|
850b15fe13 | ||
|
|
9eda78eda5 | ||
|
|
df97a5071f | ||
|
|
1c60b50e2e | ||
|
|
c3301a1653 | ||
|
|
abcb21c69a | ||
|
|
475b4601ca | ||
|
|
49e3d2c4b4 | ||
|
|
f7bf2157f3 | ||
|
|
125f10a60f | ||
|
|
5502dce556 | ||
|
|
084e8c2950 | ||
|
|
3c1a7f2641 | ||
|
|
f10d4139fe | ||
|
|
7e7e494b31 | ||
|
|
99b705d44f | ||
|
|
e0586c3afa | ||
|
|
379d9d6298 | ||
|
|
2c35257eec | ||
|
|
ed90774f53 | ||
|
|
96ca177c31 | ||
|
|
226400a5bc | ||
|
|
57ceabb260 | ||
|
|
b85ee953b7 | ||
|
|
b235227119 | ||
|
|
5c9c7f4ff4 | ||
|
|
82b38341bf | ||
|
|
4a90e9fbd9 | ||
|
|
14d030b96c | ||
|
|
6920a88dc0 | ||
|
|
966f8df33f | ||
|
|
98bd1de1cd | ||
|
|
d94286c185 | ||
|
|
618f93dec1 | ||
|
|
317619bf62 | ||
|
|
eb238ad678 | ||
|
|
54786a6c04 | ||
|
|
00f3cb3746 | ||
|
|
e977032847 | ||
|
|
5c314e3f02 | ||
|
|
f10b4c3268 | ||
|
|
dc01c748ae | ||
|
|
bae8dc3283 | ||
|
|
056c748c5f | ||
|
|
93f2b0093c | ||
|
|
5ba370fe0a | ||
|
|
818387f24e | ||
|
|
a9d6c318fd | ||
|
|
2aa58164ab | ||
|
|
df08d7f3ff | ||
|
|
3dd292be46 | ||
|
|
e29260d754 | ||
|
|
d9857e1c54 | ||
|
|
0703f27d2b | ||
|
|
8a7889b9b1 | ||
|
|
af0e369c65 | ||
|
|
910950dbac | ||
|
|
4c44782d15 | ||
|
|
3b1eb51744 | ||
|
|
cf7ee67dfe | ||
|
|
290d90609b | ||
|
|
3c1cdd434a | ||
|
|
2825ac059e | ||
|
|
a6e3eda5b2 | ||
|
|
10231bc1a8 | ||
|
|
90e3a5e29f | ||
|
|
add4dfeed5 | ||
|
|
fca039a54d | ||
|
|
1b4dae5a7a | ||
|
|
37a3f818dd | ||
|
|
c3169b7dc2 | ||
|
|
d64b71cbf0 | ||
|
|
c195eece65 | ||
|
|
fa182c216e | ||
|
|
30474c424c | ||
|
|
2888f351d1 | ||
|
|
69eaef461f | ||
|
|
8d3c9f8435 | ||
|
|
d8a91453d1 | ||
|
|
50c87fec88 | ||
|
|
4ee5410c3d | ||
|
|
3f5e840baf | ||
|
|
2358b6670f | ||
|
|
96b8fccd2a | ||
|
|
d719cbf59d | ||
|
|
a6f1eefe55 | ||
|
|
3dead2ac8b | ||
|
|
5a1ed11924 | ||
|
|
46eae105b7 | ||
|
|
8eed576826 | ||
|
|
d643aab261 | ||
|
|
07fef25591 | ||
|
|
9352a72195 | ||
|
|
7dc6e2b899 | ||
|
|
ff3a3a9100 | ||
|
|
57fa2719dd | ||
|
|
b8b3145c5c | ||
|
|
531a183b44 | ||
|
|
739f056b0a | ||
|
|
32b77cae6c | ||
|
|
46548dd09b | ||
|
|
2434724edd | ||
|
|
87d6a0d0fe |
@@ -0,0 +1,42 @@
|
||||
freebsd_instance:
|
||||
image_family: freebsd-14-0
|
||||
|
||||
build_task:
|
||||
# Don't change this name without adjusting .github/workflows/build.yaml
|
||||
name: Build FreeBSD (Stack)
|
||||
install_script: pkg install -y postgresql16-client hs-stack git
|
||||
|
||||
only_if: |
|
||||
$CIRRUS_TAG != '' || $CIRRUS_BRANCH == 'main' || $CIRRUS_BRANCH =~ 'v*' ||
|
||||
changesInclude(
|
||||
'.github/workflows/build.yaml',
|
||||
'.github/actions/artifact-from-cirrus/**',
|
||||
'.cirrus.yml',
|
||||
'postgrest.cabal',
|
||||
'stack.yaml*',
|
||||
'**.hs'
|
||||
)
|
||||
|
||||
stack_cache:
|
||||
folders: /.stack
|
||||
fingerprint_script:
|
||||
- echo $CIRRUS_OS
|
||||
- stack --version
|
||||
- md5sum postgrest.cabal
|
||||
- md5sum stack.yaml.lock
|
||||
|
||||
stack_work_cache:
|
||||
folders: .stack-work
|
||||
fingerprint_script:
|
||||
- echo $CIRRUS_OS
|
||||
- stack --version
|
||||
- md5sum postgrest.cabal
|
||||
- md5sum stack.yaml.lock
|
||||
- find main src -type f -iname '*.hs' -exec md5sum "{}" +
|
||||
|
||||
build_script: |
|
||||
stack build -j 1 --local-bin-path . --copy-bins --stack-yaml stack-21.7.yaml
|
||||
strip postgrest
|
||||
|
||||
bin_artifacts:
|
||||
path: postgrest
|
||||
@@ -3,4 +3,18 @@ When submitting a new feature or fix:
|
||||
|
||||
- Add a new entry to the CHANGELOG - https://github.com/PostgREST/postgrest/blob/main/CHANGELOG.md#unreleased
|
||||
- If relevant, update the docs
|
||||
- Use a prefix for the PR title or commits, e.g. "fix: description of the fix".
|
||||
+ `fix`, bug fixes
|
||||
+ `feat`, new features added
|
||||
+ `perf`, performance improvements
|
||||
+ `docs`, updating the documentation
|
||||
+ `nix`, related to the Nix development environment
|
||||
+ `ci`, related to the Continuous Integration modules
|
||||
+ `test`, related to the testing modules
|
||||
+ `refactor`, refactoring code
|
||||
+ `deprecate`, deprecating a feature
|
||||
+ `changelog`, updating the CHANGELOG
|
||||
+ `chore`, maintenance (build process, updating sponsors, etc.)
|
||||
+ Other prefixes may be used if necessary
|
||||
- If there's a breaking change, add `BREAKING CHANGE` and an explanation to your commit message
|
||||
-->
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
name: Artifact from Cirrus
|
||||
|
||||
description: Waits for a specific Cirrus CI run to complete, then downloads the artifact and uploads it to the current workflow. This will silently succeed if Cirrus CI did not schedule a task within 2 minutes.
|
||||
|
||||
inputs:
|
||||
download:
|
||||
description: Name of Artifact to download from Cirrus CI
|
||||
required: true
|
||||
task:
|
||||
description: Name of Cirrus Task
|
||||
required: true
|
||||
token:
|
||||
description: GitHub Token
|
||||
required: true
|
||||
upload:
|
||||
description: Name of Artifact to upload on GitHub Actions
|
||||
required: true
|
||||
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
- shell: bash
|
||||
run: echo "GH_TOKEN=${{ inputs.token }}" >> "$GITHUB_ENV"
|
||||
- name: Wait for Check Suite to be created
|
||||
id: check-suite
|
||||
env:
|
||||
# GITHUB_SHA does weird things for pull request, so we roll our own:
|
||||
COMMIT: ${{ github.event.pull_request.head.sha || github.sha }}
|
||||
shell: bash
|
||||
run: |
|
||||
get_check_runs_url() {
|
||||
gh api "repos/{owner}/{repo}/commits/${COMMIT}/check-suites" \
|
||||
| jq -r '.check_suites[] | select(.app.slug == "cirrus-ci") | .check_runs_url'
|
||||
}
|
||||
for _ in $(seq 1 12); do
|
||||
check_runs_url="$(get_check_runs_url)"
|
||||
if [ -z "$check_runs_url" ]; then
|
||||
echo "Cirrus CI task has not started, yet. Waiting..."
|
||||
sleep 10
|
||||
else
|
||||
echo "check_runs_url=$check_runs_url" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
done
|
||||
>&2 echo "Cirrus CI check suite not found. Is Cirrus CI enabled for this repo?"
|
||||
- name: Find task by name
|
||||
id: find-task
|
||||
if: steps.check-suite.outputs.check_runs_url
|
||||
shell: bash
|
||||
run: |
|
||||
get_number_of_tasks() {
|
||||
gh api "${{ steps.check-suite.outputs.check_runs_url }}" \
|
||||
| jq -r '.check_runs | map(select(.name == "${{ inputs.task }}")) | length'
|
||||
}
|
||||
tasks="$(get_number_of_tasks)"
|
||||
case "$tasks" in
|
||||
0)
|
||||
echo "Task not found, assuming it's skipped intentionally..."
|
||||
exit 0
|
||||
;;
|
||||
1)
|
||||
echo "task_found=1" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
;;
|
||||
*)
|
||||
>&2 echo "More than 1 task with the same name found. Don't know what to do..."
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
- name: Wait for Cirrus CI to complete task
|
||||
if: steps.find-task.outputs.task_found
|
||||
shell: bash
|
||||
run: |
|
||||
get_conclusion() {
|
||||
gh api "${{ steps.check-suite.outputs.check_runs_url }}" \
|
||||
| jq -r '.check_runs[] | select(.name == "${{ inputs.task }}" and .status == "completed") | .conclusion'
|
||||
}
|
||||
while true; do
|
||||
conclusion="$(get_conclusion)"
|
||||
if [ -z "$conclusion" ]; then
|
||||
echo "Cirrus CI task has not completed, yet. Waiting..."
|
||||
sleep 30
|
||||
else
|
||||
if [ "$conclusion" == "success" ]; then
|
||||
break
|
||||
else
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
done
|
||||
- name: Download artifact from Cirrus CI
|
||||
if: steps.find-task.outputs.task_found
|
||||
id: download
|
||||
shell: bash
|
||||
run: |
|
||||
get_external_id() {
|
||||
gh api "${{ steps.check-suite.outputs.check_runs_url }}" \
|
||||
| jq -er '.check_runs[] | select(.name == "${{ inputs.task }}") | .external_id'
|
||||
}
|
||||
archive="$(mktemp)"
|
||||
artifacts="$(mktemp -d)"
|
||||
until curl --no-progress-meter --fail -o "${archive}" \
|
||||
"https://api.cirrus-ci.com/v1/artifact/task/$(get_external_id)/${{ inputs.download }}.zip"
|
||||
do
|
||||
# This happens when a tag is pushed on the same commit. In this case the
|
||||
# job is immediately marked as "completed" for us, so we end up here after a few
|
||||
# seconds - but the actual Cirrus CI task is still running and didn't produce its artifact, yet.
|
||||
echo "Artifact not found on Cirrus CI, yet. Waiting..."
|
||||
sleep 30
|
||||
done
|
||||
unzip "${archive}" -d "${artifacts}"
|
||||
echo "artifacts=${artifacts}" >> "$GITHUB_OUTPUT"
|
||||
- name: Save artifact to GitHub Actions
|
||||
if: steps.find-task.outputs.task_found
|
||||
uses: actions/upload-artifact@0b2256b8c012f0828dc542b3febcab082c67f72b # v4.3.4
|
||||
with:
|
||||
name: ${{ inputs.upload }}
|
||||
path: ${{ steps.download.outputs.artifacts }}
|
||||
if-no-files-found: error
|
||||
@@ -0,0 +1,35 @@
|
||||
name: Cache on main
|
||||
|
||||
description: Stores caches on main and release branches only, but restores them on all branches.
|
||||
|
||||
inputs:
|
||||
path:
|
||||
description: Path(s) to cache
|
||||
required: true
|
||||
save-prs:
|
||||
description: Whether to additionally store the cache in a pull request, too. Should only be used for very small caches.
|
||||
type: boolean
|
||||
prefix:
|
||||
description: Cache key prefix to be used in both primary key and restore-keys.
|
||||
required: true
|
||||
suffix:
|
||||
description: Cache key suffix to be used only in primary key.
|
||||
required: true
|
||||
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
- uses: actions/cache@0c45773b623bea8c8e75f6c82b208c3cf94ea4f9 # v4.0.2
|
||||
if: ${{ startsWith(github.ref, 'refs/heads/') || (inputs.save-prs && startsWith(github.ref, 'refs/pull/')) }}
|
||||
with:
|
||||
path: ${{ inputs.path }}
|
||||
key: ${{ runner.os }}-${{ inputs.prefix }}-${{ inputs.suffix }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-${{ inputs.prefix }}-
|
||||
- uses: actions/cache/restore@0c45773b623bea8c8e75f6c82b208c3cf94ea4f9 # v4.0.2
|
||||
if: ${{ !startsWith(github.ref, 'refs/heads/') && !(inputs.save-prs && startsWith(github.ref, 'refs/pull/')) }}
|
||||
with:
|
||||
path: ${{ inputs.path }}
|
||||
key: ${{ runner.os }}-${{ inputs.prefix }}-${{ inputs.suffix }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-${{ inputs.prefix }}-
|
||||
@@ -0,0 +1,25 @@
|
||||
name: Setup Nix
|
||||
|
||||
description: Installs nix, sets up cachix and installs a subset of tooling.
|
||||
|
||||
inputs:
|
||||
authToken:
|
||||
description: Token to pass to cachix
|
||||
tools:
|
||||
description: Tools to install with nix-env -iA <tools>
|
||||
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
- uses: nixbuild/nix-quick-install-action@60e9c39264d4714139af3cdf15f691b19eec3530 # v28
|
||||
with:
|
||||
nix_conf: |-
|
||||
always-allow-substitutes = true
|
||||
max-jobs = auto
|
||||
- uses: cachix/cachix-action@ad2ddac53f961de1989924296a1f236fcfbaa4fc # v15
|
||||
with:
|
||||
name: postgrest
|
||||
authToken: ${{ inputs.authToken }}
|
||||
- if: ${{ inputs.tools }}
|
||||
run: nix-env -f default.nix -iA ${{ inputs.tools }}
|
||||
shell: bash
|
||||
@@ -0,0 +1,18 @@
|
||||
codecov:
|
||||
branch: main
|
||||
require_ci_to_pass: false
|
||||
|
||||
comment: false
|
||||
|
||||
coverage:
|
||||
status:
|
||||
project:
|
||||
default:
|
||||
target: auto
|
||||
threshold: 1%
|
||||
only_pulls: false
|
||||
patch:
|
||||
default:
|
||||
target: auto
|
||||
threshold: 1%
|
||||
only_pulls: true
|
||||
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
|
||||
"extends": [
|
||||
"config:best-practices"
|
||||
],
|
||||
"baseBranches": [
|
||||
"main",
|
||||
"/^v[0-9]+/"
|
||||
],
|
||||
"rebaseWhen": "conflicted",
|
||||
"packageRules": [
|
||||
{
|
||||
"matchBaseBranches": [ "/^v[0-9]+/" ],
|
||||
"groupName": "all dependencies"
|
||||
},
|
||||
{
|
||||
"matchPackageNames": ["docutils"],
|
||||
"allowedVersions": "<0.21.0"
|
||||
},
|
||||
{
|
||||
"matchPackageNames": ["macos"],
|
||||
"allowedVersions": "<13"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
#!/bin/bash
|
||||
set -Eeuo pipefail
|
||||
|
||||
# This script builds PostgREST in a remote ARM server
|
||||
|
||||
[ -z "$1" ] && { echo "Missing 1st argument: PostgREST github commit SHA"; exit 1; }
|
||||
[ -z "$2" ] && { echo "Missing 2nd argument: Build environment directory name"; exit 1; }
|
||||
[ -z "$3" ] && { echo "Missing 3rd argument: GHC version"; exit 1; }
|
||||
|
||||
PGRST_GITHUB_COMMIT="$1"
|
||||
SCRIPT_DIR="$2"
|
||||
|
||||
DOCKER_BUILD_DIR="$SCRIPT_DIR/docker-env"
|
||||
# latest is a shortcut documented on https://www.haskell.org/ghcup/guide/#tags-and-shortcuts
|
||||
CABAL_VERSION="latest"
|
||||
GHC_VERSION="$3"
|
||||
|
||||
install_packages() {
|
||||
sudo apt-get update -y
|
||||
sudo apt-get upgrade -y
|
||||
sudo apt-get install -y git build-essential curl libffi-dev libffi7 libgmp-dev libgmp10 libncurses-dev libncurses5 libtinfo5 llvm libnuma-dev zlib1g-dev libpq-dev jq gcc
|
||||
sudo apt-get clean
|
||||
}
|
||||
|
||||
install_ghcup() {
|
||||
export BOOTSTRAP_HASKELL_NONINTERACTIVE=1
|
||||
export BOOTSTRAP_HASKELL_MINIMAL=1
|
||||
curl --proto '=https' --tlsv1.2 -sSf https://get-ghcup.haskell.org | sh
|
||||
source ~/.ghcup/env
|
||||
}
|
||||
|
||||
install_cabal() {
|
||||
ghcup upgrade
|
||||
ghcup install cabal $CABAL_VERSION
|
||||
ghcup set cabal $CABAL_VERSION
|
||||
}
|
||||
|
||||
install_ghc() {
|
||||
ghcup upgrade
|
||||
ghcup install ghc $GHC_VERSION
|
||||
ghcup set ghc $GHC_VERSION
|
||||
}
|
||||
|
||||
install_packages
|
||||
|
||||
# Add ghcup to the PATH for this session
|
||||
[ -f ~/.ghcup/env ] && source ~/.ghcup/env
|
||||
|
||||
ghcup --version || install_ghcup
|
||||
ghcup set cabal $CABAL_VERSION || install_cabal
|
||||
ghcup set ghc $GHC_VERSION || install_ghc
|
||||
|
||||
cd ~/$SCRIPT_DIR
|
||||
|
||||
# Clone the repository and build the project
|
||||
git clone https://github.com/PostgREST/postgrest.git
|
||||
cd postgrest
|
||||
git checkout $PGRST_GITHUB_COMMIT
|
||||
cabal v2-update && cabal v2-build
|
||||
|
||||
# Strip unused symbols from executable
|
||||
PGRST_BIN=$(cabal exec which postgrest | tail -1)
|
||||
strip $PGRST_BIN
|
||||
|
||||
# Copy the built binary to the Dockerfile directory
|
||||
cp $PGRST_BIN ~/$DOCKER_BUILD_DIR
|
||||
|
||||
# Move and compress the built binary
|
||||
mkdir -p ~/$SCRIPT_DIR/result
|
||||
mv $PGRST_BIN ~/$SCRIPT_DIR/result
|
||||
cd ~/$SCRIPT_DIR
|
||||
tar -cJf result.tar.xz result
|
||||
@@ -0,0 +1,18 @@
|
||||
# PostgREST docker hub image
|
||||
|
||||
FROM ubuntu:noble@sha256:2e863c44b718727c860746568e1d54afd13b2fa71b160f5cd9058fc436217b30 AS postgrest
|
||||
|
||||
RUN apt-get update -y \
|
||||
&& apt install -y --no-install-recommends libpq-dev zlib1g-dev jq gcc libnuma-dev \
|
||||
&& apt-get clean \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY postgrest /usr/bin/postgrest
|
||||
|
||||
EXPOSE 3000
|
||||
|
||||
USER 1000
|
||||
|
||||
# Use the array form to avoid running the command using bash, which does not handle `SIGTERM` properly.
|
||||
# See https://docs.docker.com/compose/faq/#why-do-my-services-take-10-seconds-to-recreate-or-stop
|
||||
CMD ["postgrest"]
|
||||
@@ -0,0 +1,50 @@
|
||||
#!/bin/bash
|
||||
set -Eeuo pipefail
|
||||
|
||||
# This script publishes the Docker ARM images to Docker Hub.
|
||||
|
||||
[ -z "$1" ] && { echo "Missing 1st argument: PostgREST github commit SHA"; exit 1; }
|
||||
[ -z "$2" ] && { echo "Missing 2nd argument: Docker repo"; exit 1; }
|
||||
[ -z "$3" ] && { echo "Missing 3rd argument: Docker username"; exit 1; }
|
||||
[ -z "$4" ] && { echo "Missing 4th argument: Docker password"; exit 1; }
|
||||
[ -z "$5" ] && { echo "Missing 5th argument: Build environment directory name"; exit 1; }
|
||||
[ -z "$6" ] && { echo "Missing 6th argument: PostgREST version"; exit 1; }
|
||||
|
||||
PGRST_GITHUB_COMMIT="$1"
|
||||
DOCKER_REPO="$2"
|
||||
DOCKER_USER="$3"
|
||||
DOCKER_PASS="$4"
|
||||
SCRIPT_DIR="$5"
|
||||
PGRST_VERSION="$6"
|
||||
|
||||
DOCKER_BUILD_DIR="$SCRIPT_DIR/docker-env"
|
||||
|
||||
clean_env()
|
||||
{
|
||||
sudo docker logout
|
||||
}
|
||||
|
||||
# Login to Docker
|
||||
sudo docker logout
|
||||
{ echo $DOCKER_PASS | sudo docker login -u $DOCKER_USER --password-stdin; } || { echo "Couldn't login to docker"; exit 1; }
|
||||
|
||||
trap clean_env sigint sigterm exit
|
||||
|
||||
# Move to the docker build environment
|
||||
cd ~/$DOCKER_BUILD_DIR
|
||||
|
||||
# Push final images to Docker hub
|
||||
# NOTE: This command publishes a separate ARM image because the builds cannot
|
||||
# be added to the manifest if they are not in the registry beforehand.
|
||||
# This image must be manually deleted from Docker Hub at the end of the process.
|
||||
sudo docker buildx build --build-arg PGRST_GITHUB_COMMIT=$PGRST_GITHUB_COMMIT \
|
||||
-t $DOCKER_REPO/postgrest:$PGRST_VERSION-arm \
|
||||
--push .
|
||||
|
||||
# Add the arm images to the manifest
|
||||
# NOTE: This assumes that there already is a `postgrest:<version>` image
|
||||
# for the amd64 architecture pushed to Docker Hub
|
||||
sudo docker buildx imagetools create --append -t $DOCKER_REPO/postgrest:$PGRST_VERSION $DOCKER_REPO/postgrest:$PGRST_VERSION-arm
|
||||
[ "$PGRST_VERSION" != "devel" ] && sudo docker buildx imagetools create --append -t $DOCKER_REPO/postgrest:latest $DOCKER_REPO/postgrest:$PGRST_VERSION-arm
|
||||
|
||||
sudo docker logout
|
||||
@@ -0,0 +1,203 @@
|
||||
name: Build
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
secrets:
|
||||
CACHIX_AUTH_TOKEN:
|
||||
required: false
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
- v[0-9]+
|
||||
paths:
|
||||
- .github/workflows/build.yaml
|
||||
- .github/actions/**
|
||||
- .github/scripts/**
|
||||
- .github/*
|
||||
- '*.nix'
|
||||
- nix/**
|
||||
- .cirrus.yml
|
||||
- cabal.project*
|
||||
- postgrest.cabal
|
||||
- stack.yaml*
|
||||
- '**.hs'
|
||||
- '!**.md'
|
||||
|
||||
concurrency:
|
||||
# Terminate all previous runs of the same workflow for pull requests
|
||||
group: build-${{ github.head_ref || github.run_id }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
static:
|
||||
name: Nix - Linux static
|
||||
runs-on: ubuntu-22.04
|
||||
steps:
|
||||
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
|
||||
- name: Setup Nix Environment
|
||||
uses: ./.github/actions/setup-nix
|
||||
with:
|
||||
authToken: '${{ secrets.CACHIX_AUTH_TOKEN }}'
|
||||
|
||||
- name: Build static executable
|
||||
run: nix-build -A postgrestStatic
|
||||
- name: Save built executable as artifact
|
||||
uses: actions/upload-artifact@0b2256b8c012f0828dc542b3febcab082c67f72b # v4.3.4
|
||||
with:
|
||||
name: postgrest-linux-static-x64
|
||||
path: result/bin/postgrest
|
||||
if-no-files-found: error
|
||||
|
||||
- name: Build Docker image
|
||||
run: nix-build -A docker.image --out-link postgrest-docker.tar.gz
|
||||
- name: Save built Docker image as artifact
|
||||
uses: actions/upload-artifact@0b2256b8c012f0828dc542b3febcab082c67f72b # v4.3.4
|
||||
with:
|
||||
name: postgrest-docker-x64
|
||||
path: postgrest-docker.tar.gz
|
||||
if-no-files-found: error
|
||||
|
||||
|
||||
macos:
|
||||
name: Nix - MacOS
|
||||
runs-on: macos-12
|
||||
steps:
|
||||
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
|
||||
- name: Setup Nix Environment
|
||||
uses: ./.github/actions/setup-nix
|
||||
with:
|
||||
authToken: '${{ secrets.CACHIX_AUTH_TOKEN }}'
|
||||
- name: Install gnu sed
|
||||
run: brew install gnu-sed
|
||||
|
||||
- name: Build everything
|
||||
run: |
|
||||
# The --dry-run will give us a list of derivations to download from cachix and
|
||||
# derivations to build. We only take those that would have to be built and then build
|
||||
# those explicitly. This has the advantage that pure verification will not include
|
||||
# a download anymore, making it much faster. If something needs to be built, only
|
||||
# the dependencies required to do so will be downloaded, but not everything.
|
||||
nix-build --dry-run 2>&1 \
|
||||
| gsed -e '1,/derivations will be built:$/d' -e '/paths will be fetched/Q' \
|
||||
| xargs nix-build
|
||||
|
||||
|
||||
stack:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- name: Linux
|
||||
runs-on: ubuntu-22.04
|
||||
cache: |
|
||||
~/.stack/pantry
|
||||
~/.stack/snapshots
|
||||
~/.stack/stack.sqlite3
|
||||
# no artifact for Linux, because we use the static build
|
||||
|
||||
- name: MacOS
|
||||
runs-on: macos-12
|
||||
cache: |
|
||||
~/.stack/pantry
|
||||
~/.stack/snapshots
|
||||
~/.stack/stack.sqlite3
|
||||
artifact: postgrest-macos-x64
|
||||
|
||||
- name: Windows
|
||||
runs-on: windows-2022
|
||||
cache: |
|
||||
~\AppData\Roaming\stack\pantry
|
||||
~\AppData\Local\Programs\stack\pantry
|
||||
~\AppData\Roaming\stack\snapshots
|
||||
~\AppData\Local\Programs\stack\snapshots
|
||||
~\AppData\Roaming\stack\stack.sqlite3
|
||||
~\AppData\Local\Programs\stack\stack.sqlite3
|
||||
deps: Add-Content $env:GITHUB_PATH $env:PGBIN
|
||||
artifact: postgrest-windows-x64
|
||||
|
||||
name: Stack - ${{ matrix.name }}
|
||||
runs-on: ${{ matrix.runs-on }}
|
||||
steps:
|
||||
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
|
||||
- uses: haskell-actions/setup@ec49483bfc012387b227434aba94f59a6ecd0900 # v2.7.5
|
||||
with:
|
||||
# This must match the version in stack.yaml's resolver
|
||||
ghc-version: 9.6.5
|
||||
enable-stack: true
|
||||
stack-no-global: true
|
||||
stack-setup-ghc: true
|
||||
- name: Cache ~/.stack
|
||||
uses: ./.github/actions/cache-on-main
|
||||
with:
|
||||
path: ${{ matrix.cache }}
|
||||
prefix: stack
|
||||
suffix: ${{ hashFiles('postgrest.cabal', 'stack.yaml.lock') }}
|
||||
- name: Cache .stack-work
|
||||
uses: ./.github/actions/cache-on-main
|
||||
with:
|
||||
path: .stack-work
|
||||
save-prs: true
|
||||
prefix: stack-work-${{ hashFiles('postgrest.cabal', 'stack.yaml.lock') }}
|
||||
suffix: ${{ hashFiles('main/**/*.hs', 'src/**/*.hs') }}
|
||||
- name: Install dependencies
|
||||
if: matrix.deps
|
||||
run: ${{ matrix.deps }}
|
||||
- name: Build with Stack
|
||||
run: stack build --lock-file error-on-write --local-bin-path result --copy-bins
|
||||
- name: Strip Executable
|
||||
run: strip result/postgrest*
|
||||
- name: Save built executable as artifact
|
||||
if: matrix.artifact
|
||||
uses: actions/upload-artifact@0b2256b8c012f0828dc542b3febcab082c67f72b # v4.3.4
|
||||
with:
|
||||
name: ${{ matrix.artifact }}
|
||||
path: |
|
||||
result/postgrest
|
||||
result/postgrest.exe
|
||||
if-no-files-found: error
|
||||
|
||||
|
||||
freebsd:
|
||||
name: Stack - FreeBSD from CirrusCI
|
||||
runs-on: ubuntu-22.04
|
||||
steps:
|
||||
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
|
||||
- uses: ./.github/actions/artifact-from-cirrus
|
||||
with:
|
||||
token: ${{ github.token }}
|
||||
task: Build FreeBSD (Stack)
|
||||
download: bin
|
||||
upload: postgrest-freebsd-x64
|
||||
|
||||
|
||||
cabal:
|
||||
strategy:
|
||||
matrix:
|
||||
ghc: ['9.6.4', '9.8.2']
|
||||
fail-fast: false
|
||||
name: Cabal - Linux GHC ${{ matrix.ghc }}
|
||||
runs-on: ubuntu-22.04
|
||||
steps:
|
||||
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
|
||||
- uses: haskell-actions/setup@ec49483bfc012387b227434aba94f59a6ecd0900 # v2.7.5
|
||||
with:
|
||||
ghc-version: ${{ matrix.ghc }}
|
||||
- name: Cache .cabal
|
||||
uses: ./.github/actions/cache-on-main
|
||||
with:
|
||||
path: |
|
||||
~/.cabal/packages
|
||||
~/.cabal/store
|
||||
prefix: cabal-${{ matrix.ghc }}
|
||||
suffix: ${{ hashFiles('postgrest.cabal', 'cabal.project', 'cabal.project.freeze') }}
|
||||
- name: Cache dist-newstyle
|
||||
uses: ./.github/actions/cache-on-main
|
||||
with:
|
||||
path: dist-newstyle
|
||||
save-prs: true
|
||||
prefix: cabal-${{ matrix.ghc }}-dist-newstyle-${{ hashFiles('postgrest.cabal', 'cabal.project', 'cabal.project.freeze') }}
|
||||
suffix: ${{ hashFiles('**/*.hs') }}
|
||||
- name: Install dependencies
|
||||
run: cabal build --only-dependencies --enable-tests --enable-benchmarks
|
||||
- name: Build
|
||||
run: cabal build --enable-tests --enable-benchmarks all
|
||||
@@ -0,0 +1,32 @@
|
||||
name: Check
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
secrets:
|
||||
CACHIX_AUTH_TOKEN:
|
||||
required: false
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
- v[0-9]+
|
||||
|
||||
concurrency:
|
||||
# Terminate all previous runs of the same workflow for pull requests
|
||||
group: style-${{ github.head_ref || github.run_id }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
lint-style:
|
||||
name: Lint & Style
|
||||
runs-on: ubuntu-22.04
|
||||
steps:
|
||||
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
|
||||
- name: Setup Nix Environment
|
||||
uses: ./.github/actions/setup-nix
|
||||
with:
|
||||
authToken: '${{ secrets.CACHIX_AUTH_TOKEN }}'
|
||||
tools: style.lint.bin style.styleCheck.bin
|
||||
- name: Run linter (check locally with `nix-shell --run postgrest-lint`)
|
||||
run: postgrest-lint
|
||||
- name: Run style check (auto-format with `nix-shell --run postgrest-style`)
|
||||
run: postgrest-style-check
|
||||
@@ -0,0 +1,362 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- v[0-9]+
|
||||
tags:
|
||||
- devel
|
||||
- v*
|
||||
|
||||
concurrency:
|
||||
# Terminate all previous runs of the same workflow for the same tag, but never
|
||||
# cancel for the main / release branch pipelines.
|
||||
group: ci-${{ (github.ref_type == 'tag' && github.ref) || github.run_id }}
|
||||
# TODO: Enable this once https://github.com/orgs/community/discussions/13015 is solved
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
check:
|
||||
name: Check
|
||||
if: startsWith(github.ref, 'refs/heads/')
|
||||
uses: ./.github/workflows/check.yaml
|
||||
secrets:
|
||||
CACHIX_AUTH_TOKEN: ${{ secrets.CACHIX_AUTH_TOKEN }}
|
||||
|
||||
|
||||
docs:
|
||||
name: Docs
|
||||
if: startsWith(github.ref, 'refs/heads/')
|
||||
uses: ./.github/workflows/docs.yaml
|
||||
secrets:
|
||||
CACHIX_AUTH_TOKEN: ${{ secrets.CACHIX_AUTH_TOKEN }}
|
||||
|
||||
|
||||
test:
|
||||
name: Test
|
||||
if: startsWith(github.ref, 'refs/heads/')
|
||||
uses: ./.github/workflows/test.yaml
|
||||
secrets:
|
||||
CACHIX_AUTH_TOKEN: ${{ secrets.CACHIX_AUTH_TOKEN }}
|
||||
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
|
||||
|
||||
|
||||
build:
|
||||
name: Build
|
||||
uses: ./.github/workflows/build.yaml
|
||||
secrets:
|
||||
CACHIX_AUTH_TOKEN: ${{ secrets.CACHIX_AUTH_TOKEN }}
|
||||
|
||||
|
||||
arm:
|
||||
name: Build / Cabal - aarch64 GHC 9.4.8
|
||||
if: vars.SSH_ARM_ENABLED
|
||||
runs-on: ubuntu-22.04
|
||||
outputs:
|
||||
remotepath: ${{ steps.Remote-Dir.outputs.remotepath }}
|
||||
env:
|
||||
GITHUB_COMMIT: ${{ github.sha }}
|
||||
GHC_VERSION: '9.4.8'
|
||||
steps:
|
||||
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
|
||||
- id: Remote-Dir
|
||||
name: Unique directory name for the remote build
|
||||
run: echo "remotepath=postgrest-build-$(uuidgen)" >> "$GITHUB_OUTPUT"
|
||||
- name: Copy script files to the remote server
|
||||
uses: appleboy/scp-action@master
|
||||
with:
|
||||
host: ${{ secrets.SSH_ARM_HOST }}
|
||||
username: ubuntu
|
||||
key: ${{ secrets.SSH_ARM_PRIVATE_KEY }}
|
||||
fingerprint: ${{ secrets.SSH_ARM_FINGERPRINT }}
|
||||
source: ".github/scripts/arm/*"
|
||||
target: ${{ steps.Remote-Dir.outputs.remotepath }}
|
||||
strip_components: 3
|
||||
- name: Build ARM
|
||||
uses: appleboy/ssh-action@master
|
||||
env:
|
||||
REMOTE_DIR: ${{ steps.Remote-Dir.outputs.remotepath }}
|
||||
with:
|
||||
host: ${{ secrets.SSH_ARM_HOST }}
|
||||
username: ubuntu
|
||||
key: ${{ secrets.SSH_ARM_PRIVATE_KEY }}
|
||||
fingerprint: ${{ secrets.SSH_ARM_FINGERPRINT }}
|
||||
command_timeout: 120m
|
||||
script_stop: true
|
||||
envs: GITHUB_COMMIT,REMOTE_DIR,GHC_VERSION
|
||||
script: bash ~/$REMOTE_DIR/build.sh "$GITHUB_COMMIT" "$REMOTE_DIR" "$GHC_VERSION"
|
||||
- name: Download binaries from remote server
|
||||
uses: nicklasfrahm/scp-action@main
|
||||
with:
|
||||
direction: download
|
||||
host: ${{ secrets.SSH_ARM_HOST }}
|
||||
username: ubuntu
|
||||
key: ${{ secrets.SSH_ARM_PRIVATE_KEY }}
|
||||
fingerprint: ${{ secrets.SSH_ARM_FINGERPRINT }}
|
||||
source: "${{ steps.Remote-Dir.outputs.remotepath }}/result.tar.xz"
|
||||
target: "result.tar.xz"
|
||||
- name: Extract downloaded binaries
|
||||
run: tar -xvf result.tar.xz && rm result.tar.xz
|
||||
- name: Save aarch64 executable as artifact
|
||||
uses: actions/upload-artifact@0b2256b8c012f0828dc542b3febcab082c67f72b # v4.3.4
|
||||
with:
|
||||
name: postgrest-ubuntu-aarch64
|
||||
path: result/postgrest
|
||||
if-no-files-found: error
|
||||
|
||||
|
||||
tag:
|
||||
name: Release / Tag
|
||||
concurrency:
|
||||
# Never tag outdated commits on the main branch by skipping superseded commits
|
||||
group: ci-tag-${{ (github.ref == 'refs/heads/main' && github.ref) || github.run_id }}
|
||||
# TODO: Enable this once https://github.com/orgs/community/discussions/13015 is solved
|
||||
cancel-in-progress: false
|
||||
if: |
|
||||
vars.RELEASE_ENABLED &&
|
||||
startsWith(github.ref, 'refs/heads/') &&
|
||||
needs.docs.result == 'success' &&
|
||||
needs.test.result == 'success' &&
|
||||
needs.build.result == 'success' &&
|
||||
(needs.arm.result == 'skipped' || success())
|
||||
permissions:
|
||||
contents: write
|
||||
runs-on: ubuntu-22.04
|
||||
needs:
|
||||
- docs
|
||||
- test
|
||||
- build
|
||||
- arm
|
||||
steps:
|
||||
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
|
||||
with:
|
||||
ssh-key: ${{ secrets.POSTGREST_SSH_KEY }}
|
||||
- name: Tag latest commit
|
||||
run: |
|
||||
cabal_version="$(grep -oP '^version:\s*\K.*' postgrest.cabal)"
|
||||
|
||||
if [[ "$cabal_version" == *.*.* ]]; then
|
||||
git fetch --tags
|
||||
|
||||
if [ -z "$(git tag --list "v$cabal_version")" ]; then
|
||||
git tag "v$cabal_version"
|
||||
git push origin "v$cabal_version"
|
||||
fi
|
||||
else
|
||||
git tag -f "devel"
|
||||
git push -f origin "devel"
|
||||
fi
|
||||
|
||||
|
||||
prepare:
|
||||
name: Release / Prepare
|
||||
if: |
|
||||
startsWith(github.ref, 'refs/tags/') &&
|
||||
needs.build.result == 'success' &&
|
||||
(needs.arm.result == 'skipped' || success())
|
||||
runs-on: ubuntu-22.04
|
||||
needs:
|
||||
- build
|
||||
- arm
|
||||
steps:
|
||||
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
|
||||
- name: Check the version to be released
|
||||
run: |
|
||||
cabal_version="$(grep -oP '^version:\s*\K.*' postgrest.cabal)"
|
||||
|
||||
if [ "${GITHUB_REF_NAME}" != "devel" ] && [ "${GITHUB_REF_NAME}" != "v$cabal_version" ]; then
|
||||
echo "Tagged version ($GITHUB_REF_NAME) does not match the one in postgrest.cabal (v$cabal_version). Aborting release..."
|
||||
exit 1
|
||||
fi
|
||||
- name: Identify changes from CHANGELOG.md
|
||||
run: |
|
||||
if [ "${GITHUB_REF_NAME}" == "devel" ]; then
|
||||
echo "Getting unreleased changes..."
|
||||
sed -n "1,/## Unreleased/d;/## \[/q;p" CHANGELOG.md > CHANGES.md
|
||||
else
|
||||
version="$(grep -oP '^version:\s*\K.*' postgrest.cabal)"
|
||||
echo "Propper release, getting changes for version $version ..."
|
||||
sed -n "1,/## \[$version\]/d;/## \[/q;p" CHANGELOG.md > CHANGES.md
|
||||
fi
|
||||
|
||||
echo "Relevant extract from CHANGELOG.md:"
|
||||
cat CHANGES.md
|
||||
- name: Save CHANGES.md as artifact
|
||||
uses: actions/upload-artifact@0b2256b8c012f0828dc542b3febcab082c67f72b # v4.3.4
|
||||
with:
|
||||
name: release-changes
|
||||
path: CHANGES.md
|
||||
if-no-files-found: error
|
||||
|
||||
|
||||
github:
|
||||
name: Release / GitHub
|
||||
permissions:
|
||||
contents: write
|
||||
runs-on: ubuntu-22.04
|
||||
needs:
|
||||
- prepare
|
||||
if: success() || needs.prepare.result == 'success'
|
||||
steps:
|
||||
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
|
||||
- name: Download all artifacts
|
||||
uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8
|
||||
with:
|
||||
path: artifacts
|
||||
- name: Create release bundle with archives for all builds
|
||||
run: |
|
||||
find artifacts -type f -iname postgrest -exec chmod +x {} \;
|
||||
|
||||
mkdir -p release-bundle
|
||||
|
||||
tar cJvf "release-bundle/postgrest-${GITHUB_REF_NAME}-linux-static-x64.tar.xz" \
|
||||
-C artifacts/postgrest-linux-static-x64 postgrest
|
||||
|
||||
tar cJvf "release-bundle/postgrest-${GITHUB_REF_NAME}-macos-x64.tar.xz" \
|
||||
-C artifacts/postgrest-macos-x64 postgrest
|
||||
|
||||
tar cJvf "release-bundle/postgrest-${GITHUB_REF_NAME}-freebsd-x64.tar.xz" \
|
||||
-C artifacts/postgrest-freebsd-x64 postgrest
|
||||
|
||||
tar cJvf "release-bundle/postgrest-${GITHUB_REF_NAME}-ubuntu-aarch64.tar.xz" \
|
||||
-C artifacts/postgrest-ubuntu-aarch64 postgrest
|
||||
|
||||
zip "release-bundle/postgrest-${GITHUB_REF_NAME}-windows-x64.zip" \
|
||||
artifacts/postgrest-windows-x64/postgrest.exe
|
||||
|
||||
- name: Save release bundle
|
||||
uses: actions/upload-artifact@0b2256b8c012f0828dc542b3febcab082c67f72b # v4.3.4
|
||||
with:
|
||||
name: release-bundle
|
||||
path: release-bundle
|
||||
if-no-files-found: error
|
||||
|
||||
- name: Publish release on GitHub
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
echo "Releasing version ${GITHUB_REF_NAME} on GitHub..."
|
||||
|
||||
if [ "${GITHUB_REF_NAME}" == "devel" ]; then
|
||||
# To replace the existing release, we must first delete the old assets,
|
||||
# then modify the release, then add the new assets.
|
||||
gh release view devel --json assets \
|
||||
| jq -r '.assets[] | .name' \
|
||||
| xargs -rn1 \
|
||||
gh release delete-asset -y devel
|
||||
gh release edit devel \
|
||||
-t devel \
|
||||
--verify-tag \
|
||||
-F artifacts/release-changes/CHANGES.md \
|
||||
--prerelease
|
||||
gh release upload --clobber devel release-bundle/*
|
||||
else
|
||||
gh release create "${GITHUB_REF_NAME}" \
|
||||
-t "${GITHUB_REF_NAME}" \
|
||||
--verify-tag \
|
||||
-F artifacts/release-changes/CHANGES.md \
|
||||
release-bundle/*
|
||||
fi
|
||||
|
||||
|
||||
docker:
|
||||
name: Release / Docker Hub
|
||||
runs-on: ubuntu-22.04
|
||||
needs:
|
||||
- prepare
|
||||
if: |
|
||||
vars.DOCKER_REPO && vars.DOCKER_USER &&
|
||||
(success() || needs.prepare.result == 'success')
|
||||
env:
|
||||
DOCKER_REPO: ${{ vars.DOCKER_REPO }}
|
||||
DOCKER_USER: ${{ vars.DOCKER_USER }}
|
||||
DOCKER_PASS: ${{ secrets.DOCKER_PASS }}
|
||||
steps:
|
||||
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
|
||||
- name: Download Docker image
|
||||
uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8
|
||||
with:
|
||||
name: postgrest-docker-x64
|
||||
- name: Publish images on Docker Hub
|
||||
run: |
|
||||
docker login -u "$DOCKER_USER" -p "$DOCKER_PASS"
|
||||
docker load -i postgrest-docker.tar.gz
|
||||
|
||||
docker tag postgrest:latest "$DOCKER_REPO/postgrest:${GITHUB_REF_NAME}"
|
||||
docker push "$DOCKER_REPO/postgrest:${GITHUB_REF_NAME}"
|
||||
|
||||
# Only tag 'latest' for full releases
|
||||
if [ "${GITHUB_REF_NAME}" != "devel" ]; then
|
||||
echo "Pushing to 'latest' tag for full release of ${GITHUB_REF_NAME} ..."
|
||||
docker tag postgrest:latest "$DOCKER_REPO"/postgrest:latest
|
||||
docker push "$DOCKER_REPO"/postgrest:latest
|
||||
else
|
||||
echo "Skipping push to 'latest' tag for pre-release..."
|
||||
fi
|
||||
|
||||
|
||||
docker-description:
|
||||
name: Release / Docker Hub Description
|
||||
runs-on: ubuntu-22.04
|
||||
if: |
|
||||
vars.DOCKER_REPO && vars.DOCKER_USER &&
|
||||
github.ref == 'refs/tags/devel'
|
||||
steps:
|
||||
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
|
||||
- uses: peter-evans/dockerhub-description@e98e4d1628a5f3be2be7c231e50981aee98723ae # v4.0.0
|
||||
with:
|
||||
username: ${{ vars.DOCKER_USER }}
|
||||
password: ${{ secrets.DOCKER_PASS }}
|
||||
repository: ${{ vars.DOCKER_REPO }}/postgrest
|
||||
short-description: ${{ github.event.repository.description }}
|
||||
readme-filepath: ./docker-hub-readme.md
|
||||
|
||||
|
||||
docker-arm:
|
||||
name: Release / Docker Hub Arm
|
||||
runs-on: ubuntu-22.04
|
||||
needs:
|
||||
- arm
|
||||
- docker
|
||||
env:
|
||||
GITHUB_COMMIT: ${{ github.sha }}
|
||||
DOCKER_REPO: ${{ vars.DOCKER_REPO }}
|
||||
DOCKER_USER: ${{ vars.DOCKER_USER }}
|
||||
DOCKER_PASS: ${{ secrets.DOCKER_PASS }}
|
||||
steps:
|
||||
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
|
||||
- name: Publish images for ARM builds on Docker Hub
|
||||
uses: appleboy/ssh-action@master
|
||||
env:
|
||||
REMOTE_DIR: ${{ needs.arm.outputs.remotepath }}
|
||||
with:
|
||||
host: ${{ secrets.SSH_ARM_HOST }}
|
||||
username: ubuntu
|
||||
key: ${{ secrets.SSH_ARM_PRIVATE_KEY }}
|
||||
fingerprint: ${{ secrets.SSH_ARM_FINGERPRINT }}
|
||||
script_stop: true
|
||||
envs: GITHUB_COMMIT,DOCKER_REPO,DOCKER_USER,DOCKER_PASS,REMOTE_DIR,GITHUB_REF_NAME
|
||||
script: bash ~/$REMOTE_DIR/docker-publish.sh "$GITHUB_COMMIT" "$DOCKER_REPO" "$DOCKER_USER" "$DOCKER_PASS" "$REMOTE_DIR" "$GITHUB_REF_NAME"
|
||||
|
||||
|
||||
clean-arm:
|
||||
name: Build / Cleanup
|
||||
needs:
|
||||
- arm
|
||||
- docker-arm
|
||||
if: ${{ always() && vars.SSH_ARM_ENABLED }}
|
||||
runs-on: ubuntu-22.04
|
||||
env:
|
||||
REMOTE_DIR: ${{ needs.arm.outputs.remotepath }}
|
||||
steps:
|
||||
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
|
||||
- name: Remove uploaded files from server
|
||||
uses: appleboy/ssh-action@master
|
||||
with:
|
||||
host: ${{ secrets.SSH_ARM_HOST }}
|
||||
username: ubuntu
|
||||
key: ${{ secrets.SSH_ARM_PRIVATE_KEY }}
|
||||
fingerprint: ${{ secrets.SSH_ARM_FINGERPRINT }}
|
||||
envs: REMOTE_DIR
|
||||
script: rm -rf $REMOTE_DIR
|
||||
@@ -1,50 +1,67 @@
|
||||
name: Docs
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- v[0-9]+
|
||||
workflow_call:
|
||||
secrets:
|
||||
CACHIX_AUTH_TOKEN:
|
||||
required: false
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
- v[0-9]+
|
||||
- main
|
||||
- v[0-9]+
|
||||
paths:
|
||||
- .github/workflows/docs.yaml
|
||||
- .github/actions/setup-nix/**
|
||||
- default.nix
|
||||
- nix/**
|
||||
- docs/**
|
||||
- '!**.md'
|
||||
|
||||
concurrency:
|
||||
# Terminate all previous runs of the same workflow for pull requests
|
||||
group: docs-${{ github.head_ref || github.run_id }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: Build docs
|
||||
runs-on: ubuntu-24.04
|
||||
name: Build
|
||||
runs-on: ubuntu-22.04
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- uses: cachix/install-nix-action@13d8dd58da0234aa297dedd986986ccb8e7f3e24 # v31
|
||||
- run: nix-env -f docs/default.nix -iA build
|
||||
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
|
||||
- name: Setup Nix Environment
|
||||
uses: ./.github/actions/setup-nix
|
||||
with:
|
||||
authToken: '${{ secrets.CACHIX_AUTH_TOKEN }}'
|
||||
tools: docs.build.bin
|
||||
- run: postgrest-docs-build
|
||||
- run: git diff --exit-code HEAD locales || echo "Please commit changes to the locales/ folder after running postgrest-docs-build."
|
||||
|
||||
|
||||
spellcheck:
|
||||
name: Run spellcheck
|
||||
runs-on: ubuntu-24.04
|
||||
name: Spellcheck
|
||||
runs-on: ubuntu-22.04
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- uses: cachix/install-nix-action@13d8dd58da0234aa297dedd986986ccb8e7f3e24 # v31
|
||||
- run: nix-env -f docs/default.nix -iA spellcheck
|
||||
- run: postgrest-docs-spellcheck
|
||||
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
|
||||
- name: Setup Nix Environment
|
||||
uses: ./.github/actions/setup-nix
|
||||
with:
|
||||
authToken: '${{ secrets.CACHIX_AUTH_TOKEN }}'
|
||||
tools: docs.spellcheck.bin docs.dictcheck.bin
|
||||
- name: Run spellcheck
|
||||
run: postgrest-docs-spellcheck
|
||||
- name: Run dictcheck
|
||||
run: postgrest-docs-dictcheck
|
||||
|
||||
dictcheck:
|
||||
name: Run dictcheck
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- uses: cachix/install-nix-action@13d8dd58da0234aa297dedd986986ccb8e7f3e24 # v31
|
||||
- run: nix-env -f docs/default.nix -iA dictcheck
|
||||
- run: postgrest-docs-dictcheck
|
||||
|
||||
linkcheck:
|
||||
name: Run linkcheck
|
||||
name: Linkcheck
|
||||
if: github.base_ref == 'main'
|
||||
runs-on: ubuntu-24.04
|
||||
runs-on: ubuntu-22.04
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- uses: cachix/install-nix-action@13d8dd58da0234aa297dedd986986ccb8e7f3e24 # v31
|
||||
- run: nix-env -f docs/default.nix -iA linkcheck
|
||||
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
|
||||
- name: Setup Nix Environment
|
||||
uses: ./.github/actions/setup-nix
|
||||
with:
|
||||
authToken: '${{ secrets.CACHIX_AUTH_TOKEN }}'
|
||||
tools: docs.linkcheck.bin
|
||||
- run: postgrest-docs-linkcheck
|
||||
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
name: Upload Reports
|
||||
|
||||
on:
|
||||
workflow_run:
|
||||
workflows:
|
||||
- CI
|
||||
- Test
|
||||
branches-ignore:
|
||||
- devel
|
||||
- v[0-9]+
|
||||
- v[0-9]+.[0-9]+.[0-9]+
|
||||
types:
|
||||
- completed
|
||||
|
||||
jobs:
|
||||
loadtest:
|
||||
name: Loadtest
|
||||
permissions:
|
||||
checks: write
|
||||
runs-on: ubuntu-22.04
|
||||
if: github.event.workflow_run.conclusion == 'success' || github.event.workflow_run.conclusion == 'failure'
|
||||
steps:
|
||||
- name: Download from Artifacts
|
||||
uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8
|
||||
with:
|
||||
github-token: ${{ github.token }}
|
||||
run-id: ${{ github.event.workflow_run.id }}
|
||||
name: loadtest.md
|
||||
path: artifacts
|
||||
- name: Upload to GitHub Checks
|
||||
uses: LouisBrunner/checks-action@6b626ffbad7cc56fd58627f774b9067e6118af23 # v2.0.0
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
sha: ${{ github.event.workflow_run.head_sha }}
|
||||
name: Loadtest Results
|
||||
conclusion: neutral
|
||||
output: |
|
||||
{"summary":""}
|
||||
output_text_description_file: artifacts/loadtest.md
|
||||
@@ -0,0 +1,138 @@
|
||||
name: Test
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
secrets:
|
||||
CACHIX_AUTH_TOKEN:
|
||||
required: false
|
||||
CODECOV_TOKEN:
|
||||
required: false
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
- v[0-9]+
|
||||
paths:
|
||||
- .github/workflows/test.yaml
|
||||
- .github/workflows/report.yaml
|
||||
- .github/actions/setup-nix/**
|
||||
- default.nix
|
||||
- nix/**
|
||||
- .stylish-haskell.yaml
|
||||
- cabal.project
|
||||
- postgrest.cabal
|
||||
- '**.hs'
|
||||
- test/**
|
||||
- '!**.md'
|
||||
|
||||
concurrency:
|
||||
# Terminate all previous runs of the same workflow for pull requests
|
||||
group: test-${{ github.head_ref || github.run_id }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
coverage:
|
||||
name: Coverage
|
||||
runs-on: ubuntu-22.04
|
||||
defaults:
|
||||
run:
|
||||
# Hack for enabling color output, see:
|
||||
# https://github.com/actions/runner/issues/241#issuecomment-842566950
|
||||
shell: script -qec "bash --noprofile --norc -eo pipefail {0}"
|
||||
steps:
|
||||
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
|
||||
- name: Setup Nix Environment
|
||||
uses: ./.github/actions/setup-nix
|
||||
with:
|
||||
authToken: '${{ secrets.CACHIX_AUTH_TOKEN }}'
|
||||
tools: tests.coverage.bin tests.testDoctests.bin tests.testSpecIdempotence.bin
|
||||
|
||||
- name: Run coverage (IO tests and Spec tests against PostgreSQL 15)
|
||||
run: postgrest-coverage
|
||||
- name: Upload coverage to codecov
|
||||
uses: codecov/codecov-action@e28ff129e5465c2c0dcc6f003fc735cb6ae0c673 # v4.5.0
|
||||
with:
|
||||
files: ./coverage/codecov.json
|
||||
token: ${{ secrets.CODECOV_TOKEN }}
|
||||
|
||||
- name: Run doctests
|
||||
if: always()
|
||||
run: postgrest-test-doctests
|
||||
|
||||
- name: Check the spec tests for idempotence
|
||||
if: always()
|
||||
run: postgrest-test-spec-idempotence
|
||||
|
||||
|
||||
postgres:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
pgVersion: ["9_6", 10, 11, 12, 13, 14, 15, 16]
|
||||
name: PG ${{ matrix.pgVersion }}
|
||||
runs-on: ubuntu-22.04
|
||||
defaults:
|
||||
run:
|
||||
# Hack for enabling color output, see:
|
||||
# https://github.com/actions/runner/issues/241#issuecomment-842566950
|
||||
shell: script -qec "bash --noprofile --norc -eo pipefail {0}"
|
||||
steps:
|
||||
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
|
||||
- name: Setup Nix Environment
|
||||
uses: ./.github/actions/setup-nix
|
||||
with:
|
||||
authToken: '${{ secrets.CACHIX_AUTH_TOKEN }}'
|
||||
tools: tests.testSpec.bin tests.testIO.bin tests.testBigSchema.bin withTools.postgresql-${{ matrix.pgVersion }}.bin
|
||||
|
||||
- name: Run spec tests
|
||||
if: always()
|
||||
run: postgrest-with-postgresql-${{ matrix.pgVersion }} postgrest-test-spec
|
||||
|
||||
- name: Run IO tests
|
||||
if: always()
|
||||
run: postgrest-with-postgresql-${{ matrix.pgVersion }} postgrest-test-io -vv
|
||||
|
||||
- name: Run IO tests on a big schema
|
||||
if: always()
|
||||
run: postgrest-with-postgresql-${{ matrix.pgVersion }} postgrest-test-big-schema -vv
|
||||
|
||||
|
||||
memory:
|
||||
name: Memory
|
||||
runs-on: ubuntu-22.04
|
||||
steps:
|
||||
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
|
||||
- name: Setup Nix Environment
|
||||
uses: ./.github/actions/setup-nix
|
||||
with:
|
||||
authToken: '${{ secrets.CACHIX_AUTH_TOKEN }}'
|
||||
tools: memory.test.bin
|
||||
- name: Run memory tests
|
||||
run: postgrest-test-memory
|
||||
|
||||
|
||||
loadtest:
|
||||
name: Loadtest
|
||||
runs-on: ubuntu-22.04
|
||||
steps:
|
||||
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Setup Nix Environment
|
||||
uses: ./.github/actions/setup-nix
|
||||
with:
|
||||
authToken: '${{ secrets.CACHIX_AUTH_TOKEN }}'
|
||||
tools: loadtest.loadtestAgainst.bin loadtest.report.bin
|
||||
- uses: WyriHaximus/github-action-get-previous-tag@04e8485ecb6487243907e330d522ff60f02283ce # v1.4.0
|
||||
id: get-latest-tag
|
||||
with:
|
||||
prefix: v
|
||||
- name: Run loadtest
|
||||
run: |
|
||||
postgrest-loadtest-against main ${{ steps.get-latest-tag.outputs.tag }}
|
||||
postgrest-loadtest-report > loadtest/loadtest.md
|
||||
- name: Upload report
|
||||
uses: actions/upload-artifact@0b2256b8c012f0828dc542b3febcab082c67f72b # v4.3.4
|
||||
with:
|
||||
name: loadtest.md
|
||||
path: loadtest/loadtest.md
|
||||
if-no-files-found: error
|
||||
@@ -1,68 +0,0 @@
|
||||
# Architecture
|
||||
|
||||
This document describes the high-level architecture of PostgREST.
|
||||
|
||||
## Bird's Eye View
|
||||
|
||||
```haskell
|
||||
postgrest :: Request -> Either Error SQLStatement -> Response
|
||||
```
|
||||
|
||||
On the highest level, PostgREST processes an HTTP request, if it's accepted it builds a SQL statement for it, executes it, and produces a response.
|
||||
|
||||
## Code Map
|
||||
|
||||
This section talks briefly about various important modules.
|
||||
|
||||
The starting point of the program is `main/Main.hs`, which calls `src/PostgREST/CLI.hs` which then calls `src/PostgREST/App.hs`.
|
||||
|
||||
`App.hs` is then in charge of composing the different modules.
|
||||
|
||||
### ApiRequest.hs
|
||||
|
||||
PostgREST operates over two types of resources: database relations(tables or views) and database functions; providing different representations(depending on the media type)
|
||||
for them.
|
||||
|
||||
This module is in charge of representing the operation over an `ApiRequest` type. It parses the URL querystring following PostgREST syntax, the request headers, and the request body
|
||||
(if possible it avoids parsing the body and sends it directly to the db).
|
||||
|
||||
A request might be rejected at this level if it's invalid, e.g. providing an unknown media type to PostgREST or using an unknown HTTP method.
|
||||
|
||||
### Plan.hs
|
||||
|
||||
Using the Schema Cache, this module enables more complex functionality(like resource embedding) by enriching the ApiRequest. It generates Plan types(`ReadPlan`, `MutatePlan`)
|
||||
that then will be used to generate a SQL statement.
|
||||
|
||||
A request might be rejected at this level if it's invalid, e.g. by doing resource embedding on a nonexistent resource.
|
||||
|
||||
An OPTIONS request doesn't require a plan to be generated.
|
||||
|
||||
### Query.hs
|
||||
|
||||
This module constructs single SQL statements that can be parametrized and prepared. Only at this stage a PostgreSQL connection from the pool is used.
|
||||
|
||||
A query might fail(and be rollbacked) at this level if it doesn't comply to certain conditions, e.g. by not returning a single row when a ``Accept: application/vnd.pgrst.object`` header is specified.
|
||||
|
||||
An OPTIONS request doesn't require a query to be executed.
|
||||
|
||||
### Response.hs
|
||||
|
||||
This module constructs the HTTP response body with the right headers.
|
||||
|
||||
It builds the OpenAPI response using the schema cache.
|
||||
|
||||
### Auth.hs
|
||||
|
||||
This module provides functions to deal with JWT authorization.
|
||||
|
||||
### SchemaCache.hs
|
||||
|
||||
This queries the PostgreSQL system catalogs and caches the metadata into a SchemaCache type,
|
||||
|
||||
### AppState.hs
|
||||
|
||||
The state of the App which is kept across requests.
|
||||
|
||||
This spawns threads which are used to execute concurrent jobs.
|
||||
|
||||
Jobs include connection recover and a listener for the PostgreSQL LISTEN command.
|
||||
@@ -4,30 +4,30 @@ PostgREST ongoing development is only possible thanks to our Sponsors and Backer
|
||||
|
||||
## Sponsors
|
||||
|
||||
<table>
|
||||
<table align="center">
|
||||
<tbody>
|
||||
<tr>
|
||||
<td align="center" valign="middle">
|
||||
<a href="https://www.cybertec-postgresql.com/en/?utm_source=postgrest.org&utm_medium=referral&utm_campaign=postgrest" target="_blank">
|
||||
<img width="222px" src="static/cybertec-new.png">
|
||||
<img width="296px" src="static/cybertec.svg">
|
||||
</a>
|
||||
</td>
|
||||
<td align="center" valign="middle">
|
||||
<a href="https://www.2ndquadrant.com/en/?utm_campaign=External%20Websites&utm_source=PostgREST&utm_medium=Logo" target="_blank">
|
||||
<img width="296px" src="static/2ndquadrant.png">
|
||||
<a href="https://gnuhost.eu/?utm_source=sponsor&utm_campaign=postgrest" target="_blank">
|
||||
<img width="296px" src="static/gnuhost.png">
|
||||
</a>
|
||||
</td>
|
||||
<td align="center" valign="middle">
|
||||
<a href="https://tryretool.com/?utm_source=sponsor&utm_campaign=postgrest" target="_blank">
|
||||
<img width="296px" src="static/retool.png">
|
||||
<a href="https://neon.tech/?utm_source=sponsor&utm_campaign=postgrest" target="_blank">
|
||||
<img width="296px" src="static/neon.jpg">
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
<tr></tr>
|
||||
<tr>
|
||||
<td align="center" valign="middle">
|
||||
<a href="https://gnuhost.eu/?utm_source=sponsor&utm_campaign=postgrest" target="_blank">
|
||||
<img width="296px" src="static/gnuhost.png">
|
||||
<a href="https://code.build/?utm_source=sponsor&utm_campaign=postgrest" target="_blank">
|
||||
<img width="296px" src="static/code-build.png">
|
||||
</a>
|
||||
</td>
|
||||
<td align="center" valign="middle">
|
||||
@@ -36,8 +36,8 @@ PostgREST ongoing development is only possible thanks to our Sponsors and Backer
|
||||
</a>
|
||||
</td>
|
||||
<td align="center" valign="middle">
|
||||
<a href="https://oblivious.ai/?utm_source=sponsor&utm_campaign=postgrest" target="_blank">
|
||||
<img width="296px" src="static/oblivious.jpg">
|
||||
<a href="https://tembo.io/?utm_source=sponsor&utm_campaign=postgrest" target="_blank">
|
||||
<img width="296px" src="static/tembo.png">
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
@@ -78,6 +78,21 @@ PostgREST ongoing development is only possible thanks to our Sponsors and Backer
|
||||
<img width="222px" src="static/timescaledb.png">
|
||||
</a>
|
||||
</td>
|
||||
<td align="center" valign="middle">
|
||||
<a href="https://tryretool.com/?utm_source=sponsor&utm_campaign=postgrest" target="_blank">
|
||||
<img max-width="222px" height="88" src="static/retool.png">
|
||||
</a>
|
||||
</td>
|
||||
<td align="center" valign="middle">
|
||||
<a href="https://www.2ndquadrant.com/en/?utm_campaign=External%20Websites&utm_source=PostgREST&utm_medium=Logo" target="_blank">
|
||||
<img width="222px" src="static/2ndquadrant.png">
|
||||
</a>
|
||||
</td>
|
||||
<td align="center" valign="middle">
|
||||
<a href="https://oblivious.ai/?utm_source=sponsor&utm_campaign=postgrest" target="_blank">
|
||||
<img width="222px" src="static/oblivious.jpg">
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
@@ -5,6 +5,154 @@ This project adheres to [Semantic Versioning](http://semver.org/).
|
||||
|
||||
## Unreleased
|
||||
|
||||
## [12.2.3] - 2024-08-01
|
||||
|
||||
### Fixed
|
||||
|
||||
- #3091, Broken link in OpenAPI description `externalDocs` - @salim-b
|
||||
- #3659, Embed One-to-One relationship with different column order properly - @wolfgangwalther
|
||||
- #3504, Remove `format` from `rowFilter` parameters in OpenAPI - @dantheman2865
|
||||
- #3660, Fix regression that loaded the schema cache before the in-database configuration - @steve-chavez, @laurenceisla
|
||||
|
||||
## [12.2.2] - 2024-07-10
|
||||
|
||||
### Fixed
|
||||
|
||||
- #3093, Nested empty embeds no longer show empty values and are correctly omitted - @laurenceisla
|
||||
- #3644, Make --dump-schema work with in-database pgrst.db_schemas setting - @wolfgangwalther
|
||||
- #3644, Show number of timezones in schema cache load report - @wolfgangwalther
|
||||
- #3644, List correct enum options in OpenApi output when multiple types with same name are present - @wolfgangwalther
|
||||
- #3523, Fix schema cache loading retry without backoff - @steve-chavez
|
||||
|
||||
## [12.2.1] - 2024-06-27
|
||||
|
||||
### Fixed
|
||||
|
||||
- #3147, Don't reload schema cache on every listener failure - @steve-chavez
|
||||
|
||||
### Documentation
|
||||
|
||||
- #3592, Architecture diagram now supports dark mode and has links - @laurenceisla
|
||||
- #3616, The schema isolation diagram now supports dark mode and uses well-known schemas - @laurenceisla
|
||||
|
||||
## [12.2.0] - 2024-06-11
|
||||
|
||||
### Added
|
||||
|
||||
- #2887, Add Preference `max-affected` to limit affected resources - @taimoorzaeem
|
||||
- #3171, Add an ability to dump config via admin API - @skywriter
|
||||
- #3171, #3046, Log schema cache stats to stderr - @steve-chavez
|
||||
- #3210, Dump schema cache through admin API - @taimoorzaeem
|
||||
- #2676, Performance improvement on bulk json inserts, around 10% increase on requests per second by removing `json_typeof` from write queries - @steve-chavez
|
||||
- #3435, Add log-level=debug, for development purposes - @steve-chavez
|
||||
- #1526, Add `/metrics` endpoint on admin server - @steve-chavez
|
||||
- Exposes connection pool metrics, schema cache metrics
|
||||
- #3404, Show the failed MESSAGE or DETAIL in the `details` field of the `PGRST121` (could not parse RAISE 'PGRST') error - @laurenceisla
|
||||
- #3404, Show extra information in the `PGRST121` (could not parse RAISE 'PGRST') error - @laurenceisla
|
||||
+ Shows the failed MESSAGE or DETAIL in the `details` field
|
||||
+ Shows the correct JSON format in the `hints` field
|
||||
- #3340, Log when the LISTEN channel gets a notification - @steve-chavez
|
||||
- #3184, Log full pg version to stderr on connection - @steve-chavez
|
||||
- #3242. Add config `db-hoisted-tx-settings` to apply only hoisted function settings - @taimoorzaeem
|
||||
- #3214, #3229 Log connection pool events on log-level=debug - @steve-chavez, @laurenceisla
|
||||
|
||||
### Fixed
|
||||
|
||||
- #3237, Dump media handlers and timezones with --dump-schema - @wolfgangwalther
|
||||
- #3323, #3324, Don't hide error on LISTEN channel failure - @steve-chavez
|
||||
- #3330, Incorrect admin server `/ready` response on slow schema cache loads - @steve-chavez
|
||||
- #3345, Fix in-database configuration values not loading for `pgrst.server_trace_header` and `pgrst.server_cors_allowed_origins` - @laurenceisla
|
||||
- #3404, Clarify the `PGRST121` (could not parse RAISE 'PGRST') error message - @laurenceisla
|
||||
- #3267, Fix wrong `503 Service Unavailable` on pg error `53400` - @taimoorzaeem
|
||||
- #2985, Fix not adding `application_name` on all connection strings - @steve-chavez
|
||||
- #3424, Admin `/live` and `/ready` now differentiates a failure as 500 status - @steve-chavez
|
||||
+ 503 status is still given when postgREST is in a recovering state
|
||||
- #3478, Media Types are parsed case insensitively - @develop7
|
||||
- #3533, #3536, Fix listener silently failing on read replica - @steve-chavez
|
||||
+ If the LISTEN connection fails, it's retried with exponential backoff
|
||||
- #3414, Force listener to connect to read-write instances using `target_session_attrs` - @steve-chavez
|
||||
- #3255, Fix incorrect `413 Request Entity Too Large` on pg errors `54*` - @taimoorzaeem
|
||||
- #3549, Remove verbosity from error logs starting with "An error occurred..." and replacing it with "Failed to..." - @laurenceisla
|
||||
|
||||
### Deprecated
|
||||
|
||||
- Support for PostgreSQL versions 9.6, 10 and 11 is deprecated. From this on version onwards, PostgREST will only support non-end-of-life PostgreSQL versions. See https://www.postgresql.org/support/versioning/.
|
||||
- `Prefer: params=single-object` is deprecated. Use [a function with a single unnamed JSON parameter](https://postgrest.org/en/latest/references/api/functions.html#function-single-json) instead. - @steve-chavez
|
||||
|
||||
### Documentation
|
||||
|
||||
- #3289, Add dark mode. Can be toggled by a button in the bottom right corner. - @laurenceisla
|
||||
- #3384, Add architecture diagram and documentation - @steve-chavez
|
||||
|
||||
## [12.0.3] - 2024-05-09
|
||||
|
||||
### Fixed
|
||||
|
||||
- #3149, Misleading "Starting PostgREST.." logs on schema cache reloading - @steve-chavez
|
||||
- #3205, Fix wrong subquery error returning a status of 400 Bad Request - @steve-chavez
|
||||
- #3224, Return status code 406 for non-accepted media type instead of code 415 - @wolfgangwalther
|
||||
- #3160, Fix using select= query parameter for custom media type handlers - @wolfgangwalther
|
||||
- #3361, Clarify PGRST204(column not found) error message - @steve-chavez
|
||||
- #3373, Remove rejected mediatype `application/vnd.pgrst.object+json` from response - @taimoorzaeem
|
||||
- #3418, Fix OpenAPI not tagging a FK column correctly on O2O relationships - @laurenceisla
|
||||
- #3256, Fix wrong http status for pg error `42P17 infinite recursion` - @taimoorzaeem
|
||||
|
||||
## [12.0.2] - 2023-12-20
|
||||
|
||||
### Fixed
|
||||
|
||||
- #3124, Fix table's media type handlers not working for all schemas - @steve-chavez
|
||||
- #3126, Fix empty row on media type handler function - @steve-chavez
|
||||
|
||||
## [12.0.1] - 2023-12-12
|
||||
|
||||
### Fixed
|
||||
|
||||
- #3054, Fix not allowing special characters in JSON keys - @laurenceisla
|
||||
- #2344, Replace JSON parser error with a clearer generic message - @develop7
|
||||
- #3100, Add missing in-database configuration option for `jwt-cache-max-lifetime` - @laurenceisla
|
||||
- #3089, The any media type handler now sets `Content-Type: application/octet-stream` by default instead of `Content-Type: application/json` - @steve-chavez
|
||||
|
||||
## [12.0.0] - 2023-12-01
|
||||
|
||||
### Added
|
||||
|
||||
- #1614, Add `db-pool-automatic-recovery` configuration to disable connection retrying - @taimoorzaeem
|
||||
- #2492, Allow full response control when raising exceptions - @taimoorzaeem, @laurenceisla
|
||||
- #2771, #2983, #3062, #3055 Add `Server-Timing` response header - @taimoorzaeem, @develop7, @laurenceisla
|
||||
- #2698, Add config `jwt-cache-max-lifetime` and implement JWT caching - @taimoorzaeem
|
||||
- #2943, Add `handling=strict/lenient` for Prefer header - @taimoorzaeem
|
||||
- #2441, Add config `server-cors-allowed-origins` to specify CORS origins - @taimoorzaeem
|
||||
- #2825, SQL handlers for custom media types - @steve-chavez
|
||||
+ Solves #1548, #2699, #2763, #2170, #1462, #1102, #1374, #2901
|
||||
- #2799, Add timezone in Prefer header - @taimoorzaeem
|
||||
- #3001, Add `statement_timeout` set on functions - @taimoorzaeem
|
||||
- #3045, Apply superuser settings on impersonated roles if they have PostgreSQL 15 `GRANT SET ON PARAMETER` privilege - @steve-chavez
|
||||
- #915, Add support for aggregate functions - @timabdulla
|
||||
+ The aggregate functions SUM(), MAX(), MIN(), AVG(), and COUNT() are now supported.
|
||||
+ It's disabled by default, you can enable it with `db-aggregates-enabled`.
|
||||
- #3057, Log all internal database errors to stderr - @laurenceisla
|
||||
|
||||
### Fixed
|
||||
|
||||
- #3015, Fix unnecessary count() on RPC returning single - @steve-chavez
|
||||
- #1070, Fix HTTP status responses for upserts - @taimoorzaeem
|
||||
+ `PUT` returns `201` instead of `200` when rows are inserted
|
||||
+ `POST` with `Prefer: resolution=merge-duplicates` returns `200` instead of `201` when no rows are inserted
|
||||
- #3019, Transaction-Scoped Settings are now shown clearly in the Postgres logs - @laurenceisla
|
||||
+ Shows `set_config('pgrst.setting_name', $1)` instead of `setconfig($1, $2)`
|
||||
+ Does not apply to role settings and `app.settings.*`
|
||||
- #2420, Fix bogus message when listening on port 0 - @develop7
|
||||
- #3067, Fix Acquision Timeout errors logging to stderr when `log-level=crit` - @laurenceisla
|
||||
|
||||
### Changed
|
||||
|
||||
- Removed [raw-media-types config](https://postgrest.org/en/v11.1/references/configuration.html#raw-media-types) - @steve-chavez
|
||||
- Removed `application/octet-stream`, `text/plain`, `text/xml` [builtin support for scalar results](https://postgrest.org/en/v11.1/references/api/resource_representation.html#scalar-function-response-format) - @steve-chavez
|
||||
- Removed default `application/openapi+json` media type for [db-root-spec](https://postgrest.org/en/v11.1/references/configuration.html#db-root-spec) - @steve-chavez
|
||||
- Removed [db-use-legacy-gucs](https://postgrest.org/en/v11.2/references/configuration.html#db-use-legacy-gucs) - @laurenceisla
|
||||
+ All PostgreSQL versions now use GUCs in JSON format for [Headers, Cookies and JWT claims](https://postgrest.org/en/v12/references/transactions.html#request-headers-cookies-and-jwt-claims).
|
||||
|
||||
## [11.2.2] - 2023-10-25
|
||||
|
||||
### Fixed
|
||||
@@ -307,6 +455,11 @@ This project adheres to [Semantic Versioning](http://semver.org/).
|
||||
- #2312, Using `Prefer: return=representation` no longer returns a `Location` header - @laurenceisla
|
||||
- #1984, For the cases where one to one relationships are detected, json objects will be returned instead of json arrays of length 1
|
||||
+ If you wish to override this behavior, you can use computed relationships to return arrays again
|
||||
+ You can get the newly detected one-to-one relationships by using the `--dump-schema` option and filtering with [jq](https://github.com/jqlang/jq).
|
||||
```
|
||||
./postgrest --dump-schema \
|
||||
| jq '[.dbRelationships | .[] | .[1] | .[] | select(.relCardinality.tag == "O2O" and .relFTableIsView == false and .relTableIsView == false) | del(.relFTableIsView,.relTableIsView,.tag,.relIsSelf)]'
|
||||
```
|
||||
|
||||
## [9.0.1] - 2022-06-03
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||

|
||||

|
||||
|
||||
[](https://www.patreon.com/postgrest)
|
||||
[](http://postgrest.org)
|
||||
@@ -13,30 +13,30 @@ API than you are likely to write from scratch.
|
||||
|
||||
## Sponsors
|
||||
|
||||
<table>
|
||||
<table align="center">
|
||||
<tbody>
|
||||
<tr>
|
||||
<td align="center" valign="middle">
|
||||
<a href="https://www.cybertec-postgresql.com/en/?utm_source=postgrest.org&utm_medium=referral&utm_campaign=postgrest" target="_blank">
|
||||
<img width="222px" src="static/cybertec-new.png">
|
||||
<img width="296px" src="static/cybertec.svg">
|
||||
</a>
|
||||
</td>
|
||||
<td align="center" valign="middle">
|
||||
<a href="https://www.2ndquadrant.com/en/?utm_campaign=External%20Websites&utm_source=PostgREST&utm_medium=Logo" target="_blank">
|
||||
<img width="296px" src="static/2ndquadrant.png">
|
||||
<a href="https://gnuhost.eu/?utm_source=sponsor&utm_campaign=postgrest" target="_blank">
|
||||
<img width="296px" src="static/gnuhost.png">
|
||||
</a>
|
||||
</td>
|
||||
<td align="center" valign="middle">
|
||||
<a href="https://tryretool.com/?utm_source=sponsor&utm_campaign=postgrest" target="_blank">
|
||||
<img width="296px" src="static/retool.png">
|
||||
<a href="https://neon.tech/?utm_source=sponsor&utm_campaign=postgrest" target="_blank">
|
||||
<img width="296px" src="static/neon.jpg">
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
<tr></tr>
|
||||
<tr>
|
||||
<td align="center" valign="middle">
|
||||
<a href="https://gnuhost.eu/?utm_source=sponsor&utm_campaign=postgrest" target="_blank">
|
||||
<img width="296px" src="static/gnuhost.png">
|
||||
<a href="https://code.build/?utm_source=sponsor&utm_campaign=postgrest" target="_blank">
|
||||
<img width="296px" src="static/code-build.png">
|
||||
</a>
|
||||
</td>
|
||||
<td align="center" valign="middle">
|
||||
@@ -45,8 +45,8 @@ API than you are likely to write from scratch.
|
||||
</a>
|
||||
</td>
|
||||
<td align="center" valign="middle">
|
||||
<a href="https://oblivious.ai/?utm_source=sponsor&utm_campaign=postgrest" target="_blank">
|
||||
<img width="296px" src="static/oblivious.jpg">
|
||||
<a href="https://tembo.io/?utm_source=sponsor&utm_campaign=postgrest" target="_blank">
|
||||
<img width="296px" src="static/tembo.png">
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
@@ -66,7 +66,7 @@ Big thanks to our sponsors! You can join them by supporting PostgREST on [Patreo
|
||||
```
|
||||
## [Documentation](http://postgrest.org)
|
||||
|
||||
Latest documentation is at [postgrest.org](http://postgrest.org). You can contribute to the docs in [PostgREST/postgrest-docs](https://github.com/PostgREST/postgrest-docs).
|
||||
Latest documentation is at [postgrest.org](http://postgrest.org). You can contribute to the docs in [PostgREST/postgrest/docs](https://github.com/PostgREST/postgrest/tree/main/docs).
|
||||
|
||||
## Performance
|
||||
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
packages: postgrest.cabal
|
||||
tests: true
|
||||
package *
|
||||
ghc-options: -split-sections
|
||||
@@ -0,0 +1 @@
|
||||
index-state: hackage.haskell.org 2024-05-17T23:41:49Z
|
||||
@@ -1,20 +0,0 @@
|
||||
-- Settings to allow building with plain cabal. If this was
|
||||
-- named just cabal.project, it would interfere with the default
|
||||
-- nix build.
|
||||
|
||||
packages: .
|
||||
|
||||
-- Example of depending on a forked repository (the same dependency
|
||||
-- would be mentioned in nix/overlays/haskell-packages.nix and
|
||||
-- stack.yaml, and should refer to a main branch commit of the
|
||||
-- repository.
|
||||
--
|
||||
-- source-repository-package
|
||||
-- type: git
|
||||
-- location: https://github.com/PostgREST/hasql-pool.git
|
||||
-- tag: 4d462c4d47d762effefc7de6c85eaed55f144f1d
|
||||
|
||||
source-repository-package
|
||||
type: git
|
||||
location: https://github.com/PostgREST/postgresql-libpq.git
|
||||
tag: 890a0a16cf57dd401420fdc6c7d576fb696003bc
|
||||
@@ -1,12 +1,23 @@
|
||||
{ system ? builtins.currentSystem }:
|
||||
{ system ? builtins.currentSystem
|
||||
|
||||
, compiler ? "ghc948"
|
||||
|
||||
, # Commit of the Nixpkgs repository that we want to use.
|
||||
nixpkgsVersion ? import nix/nixpkgs-version.nix
|
||||
|
||||
, # Nix files that describe the Nixpkgs repository. We evaluate the expression
|
||||
# using `import` below.
|
||||
nixpkgs ? let inherit (nixpkgsVersion) owner repo rev tarballHash; in
|
||||
builtins.fetchTarball {
|
||||
url = "https://github.com/${owner}/${repo}/archive/${rev}.tar.gz";
|
||||
sha256 = tarballHash;
|
||||
}
|
||||
}:
|
||||
|
||||
let
|
||||
name =
|
||||
"postgrest";
|
||||
|
||||
compiler =
|
||||
"ghc924";
|
||||
|
||||
# PostgREST source files, filtered based on the rules in the .gitignore files
|
||||
# and file extensions. We want to include as litte as possible, as the files
|
||||
# added here will increase the space used in the Nix store and trigger the
|
||||
@@ -16,18 +27,6 @@ let
|
||||
(pkgs.gitignoreSource ./.)
|
||||
[ ".cabal" ".hs" ".lhs" "LICENSE" ];
|
||||
|
||||
# Commit of the Nixpkgs repository that we want to use.
|
||||
nixpkgsVersion =
|
||||
import nix/nixpkgs-version.nix;
|
||||
|
||||
# Nix files that describe the Nixpkgs repository. We evaluate the expression
|
||||
# using `import` below.
|
||||
nixpkgs =
|
||||
builtins.fetchTarball {
|
||||
url = "https://github.com/nixos/nixpkgs/archive/${nixpkgsVersion.rev}.tar.gz";
|
||||
sha256 = nixpkgsVersion.tarballHash;
|
||||
};
|
||||
|
||||
allOverlays =
|
||||
import nix/overlays;
|
||||
|
||||
@@ -36,10 +35,10 @@ let
|
||||
allOverlays.build-toolbox
|
||||
allOverlays.checked-shell-script
|
||||
allOverlays.gitignore
|
||||
allOverlays.postgis
|
||||
(allOverlays.postgresql-default { inherit patches; })
|
||||
allOverlays.postgresql-libpq
|
||||
allOverlays.postgresql-legacy
|
||||
allOverlays.postgresql-future
|
||||
allOverlays.postgis
|
||||
(allOverlays.haskell-packages { inherit compiler; })
|
||||
allOverlays.slocat
|
||||
];
|
||||
@@ -50,52 +49,28 @@ let
|
||||
|
||||
postgresqlVersions =
|
||||
[
|
||||
{
|
||||
name = "postgresql-16";
|
||||
postgresql = pkgs.postgresql_16.withPackages (p: [
|
||||
p.postgis
|
||||
(p.pg_safeupdate.overrideAttrs (old: {
|
||||
installPhase = ''
|
||||
mkdir -p $out/bin
|
||||
cp safeupdate.dylib safeupdate.so || true
|
||||
install -D safeupdate.so -t $out/lib
|
||||
'';
|
||||
}))
|
||||
]);
|
||||
}
|
||||
{ name = "postgresql-16"; postgresql = pkgs.postgresql_16.withPackages (p: [ p.postgis p.pg_safeupdate ]); }
|
||||
{ name = "postgresql-15"; postgresql = pkgs.postgresql_15.withPackages (p: [ p.postgis p.pg_safeupdate ]); }
|
||||
{ name = "postgresql-14"; postgresql = pkgs.postgresql_14.withPackages (p: [ p.postgis p.pg_safeupdate ]); }
|
||||
{ name = "postgresql-13"; postgresql = pkgs.postgresql_13.withPackages (p: [ p.postgis p.pg_safeupdate ]); }
|
||||
{ name = "postgresql-12"; postgresql = pkgs.postgresql_12.withPackages (p: [ p.postgis p.pg_safeupdate ]); }
|
||||
{ name = "postgresql-11"; postgresql = pkgs.postgresql_11.withPackages (p: [ p.postgis p.pg_safeupdate ]); }
|
||||
{ name = "postgresql-10"; postgresql = pkgs.postgresql_10.withPackages (p: [ p.postgis p.pg_safeupdate ]); }
|
||||
{ name = "postgresql-9.6"; postgresql = pkgs.postgresql_9_6.withPackages (p: [ p.postgis p.pg_safeupdate ]); }
|
||||
{ name = "postgresql-9_6"; postgresql = pkgs.postgresql_9_6.withPackages (p: [ p.postgis p.pg_safeupdate ]); }
|
||||
];
|
||||
|
||||
patches =
|
||||
pkgs.callPackage nix/patches { };
|
||||
|
||||
# Dynamic derivation for PostgREST
|
||||
postgrest =
|
||||
pkgs.haskell.packages."${compiler}".callCabal2nix name src { };
|
||||
|
||||
# Functionality that derives a fully static Haskell package based on
|
||||
# nh2/static-haskell-nix
|
||||
staticHaskellPackage =
|
||||
import nix/static-haskell-package.nix { inherit nixpkgs system compiler patches allOverlays; };
|
||||
|
||||
# Static executable.
|
||||
postgrestStatic =
|
||||
lib.justStaticExecutables (lib.dontCheck (staticHaskellPackage name src).package);
|
||||
|
||||
packagesStatic = (staticHaskellPackage name src).survey;
|
||||
staticHaskellPackage = import nix/static.nix { inherit compiler name pkgs src; };
|
||||
|
||||
# Options passed to cabal in dev tools and tests
|
||||
devCabalOptions =
|
||||
"-f dev --test-show-detail=direct";
|
||||
|
||||
profiledHaskellPackages =
|
||||
pkgs.haskell.packages."${compiler}".extend (self: super:
|
||||
pkgs.haskell.packages."${compiler}".extend (_: super:
|
||||
{
|
||||
mkDerivation =
|
||||
args:
|
||||
@@ -136,12 +111,16 @@ rec {
|
||||
pkgs.callPackage nix/tools/cabalTools.nix { inherit devCabalOptions postgrest; };
|
||||
|
||||
withTools =
|
||||
pkgs.callPackage nix/tools/withTools.nix { inherit cabalTools devCabalOptions postgresqlVersions postgrest; };
|
||||
pkgs.callPackage nix/tools/withTools.nix { inherit postgresqlVersions postgrest; };
|
||||
|
||||
# Development tools.
|
||||
devTools =
|
||||
pkgs.callPackage nix/tools/devTools.nix { inherit tests style devCabalOptions hsie withTools; };
|
||||
|
||||
# Documentation tools.
|
||||
docs =
|
||||
pkgs.callPackage nix/tools/docs.nix { };
|
||||
|
||||
# Load testing tools.
|
||||
loadtest =
|
||||
pkgs.callPackage nix/tools/loadtest.nix { inherit withTools; };
|
||||
@@ -172,8 +151,8 @@ rec {
|
||||
};
|
||||
} // pkgs.lib.optionalAttrs pkgs.stdenv.isLinux rec {
|
||||
# Static executable.
|
||||
inherit postgrestStatic;
|
||||
inherit packagesStatic;
|
||||
inherit (staticHaskellPackage) postgrestStatic;
|
||||
inherit (staticHaskellPackage) packagesStatic;
|
||||
|
||||
# Docker images and loading script.
|
||||
docker =
|
||||
|
||||
@@ -10,30 +10,30 @@ write from scratch.
|
||||
|
||||
## Sponsors
|
||||
|
||||
<table>
|
||||
<table align="center">
|
||||
<tbody>
|
||||
<tr>
|
||||
<td align="center" valign="middle">
|
||||
<a href="https://www.cybertec-postgresql.com/en/?utm_source=postgrest.org&utm_medium=referral&utm_campaign=postgrest" target="_blank">
|
||||
<img width="222px" src="https://raw.githubusercontent.com/PostgREST/postgrest/main/static/cybertec-new.png">
|
||||
<img width="296px" src="https://raw.githubusercontent.com/PostgREST/postgrest/main/static/cybertec.svg">
|
||||
</a>
|
||||
</td>
|
||||
<td align="center" valign="middle">
|
||||
<a href="https://www.2ndquadrant.com/en/?utm_campaign=External%20Websites&utm_source=PostgREST&utm_medium=Logo" target="_blank">
|
||||
<img width="296px" src="https://raw.githubusercontent.com/PostgREST/postgrest/main/static/2ndquadrant.png">
|
||||
<a href="https://gnuhost.eu/?utm_source=sponsor&utm_campaign=postgrest" target="_blank">
|
||||
<img width="296px" src="https://raw.githubusercontent.com/PostgREST/postgrest/main/static/gnuhost.png">
|
||||
</a>
|
||||
</td>
|
||||
<td align="center" valign="middle">
|
||||
<a href="https://tryretool.com/?utm_source=sponsor&utm_campaign=postgrest" target="_blank">
|
||||
<img width="296px" src="https://raw.githubusercontent.com/PostgREST/postgrest/main/static/retool.png">
|
||||
<a href="https://neon.tech/?utm_source=sponsor&utm_campaign=postgrest" target="_blank">
|
||||
<img width="296px" src="https://raw.githubusercontent.com/PostgREST/postgrest/main/static/neon.jpg">
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
<tr></tr>
|
||||
<tr>
|
||||
<td align="center" valign="middle">
|
||||
<a href="https://gnuhost.eu/?utm_source=sponsor&utm_campaign=postgrest" target="_blank">
|
||||
<img width="296px" src="https://raw.githubusercontent.com/PostgREST/postgrest/main/static/gnuhost.png">
|
||||
<a href="https://code.build/?utm_source=sponsor&utm_campaign=postgrest" target="_blank">
|
||||
<img width="296px" src="https://raw.githubusercontent.com/PostgREST/postgrest/main/static/code-build.png">
|
||||
</a>
|
||||
</td>
|
||||
<td align="center" valign="middle">
|
||||
@@ -42,8 +42,8 @@ write from scratch.
|
||||
</a>
|
||||
</td>
|
||||
<td align="center" valign="middle">
|
||||
<a href="https://oblivious.ai/?utm_source=sponsor&utm_campaign=postgrest" target="_blank">
|
||||
<img width="296px" src="https://raw.githubusercontent.com/PostgREST/postgrest/main/static/oblivious.jpg">
|
||||
<a href="https://tembo.io/?utm_source=sponsor&utm_campaign=postgrest" target="_blank">
|
||||
<img width="296px" src="https://raw.githubusercontent.com/PostgREST/postgrest/main/static/tembo.png">
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
@@ -56,13 +56,15 @@ To learn how to use this container, see the [PostgREST Docker
|
||||
documentation](https://postgrest.org/en/stable/install.html#docker).
|
||||
|
||||
You can configure the PostgREST image by setting
|
||||
[enviroment variables](https://postgrest.org/en/stable/configuration.html).
|
||||
[environment variables](https://postgrest.org/en/stable/configuration.html).
|
||||
|
||||
# How this image is built
|
||||
|
||||
The image is built from scratch using
|
||||
[Nix](https://nixos.org/nixpkgs/manual/#sec-pkgs-dockerTools) instead of a
|
||||
`Dockerfile`, which yields a higly secure and optimized image. This is also why
|
||||
`Dockerfile`, which yields a highly secure and optimized image. This is also why
|
||||
no commands are listed in the image history. See the [PostgREST
|
||||
respository](https://github.com/PostgREST/postgrest/tree/main/nix/tools/docker) for
|
||||
details on the build process and how to inspect the image.
|
||||
|
||||
This does not apply to the arm64 variant, which is based on Ubuntu.
|
||||
@@ -5,4 +5,4 @@ Pipfile.lock
|
||||
_diagrams/db.pdf
|
||||
misspellings
|
||||
unuseddict
|
||||
.history
|
||||
*.mo
|
||||
|
||||
@@ -2,19 +2,27 @@
|
||||
|
||||
PostgREST docs use the reStructuredText format, check this [cheatsheet](https://github.com/ralsina/rst-cheatsheet/blob/master/rst-cheatsheet.rst) to get acquainted with it.
|
||||
|
||||
To build the docs locally, use [nix](https://nixos.org/nix/):
|
||||
|
||||
```bash
|
||||
nix-shell
|
||||
```
|
||||
|
||||
Once in the nix-shell you have the following commands available:
|
||||
|
||||
- `postgrest-docs-build`: Build the docs.
|
||||
- `postgrest-docs-serve`: Build the docs and start a livereload server on `http://localhost:5500`.
|
||||
- `postgrest-docs-spellcheck`: Run aspell.
|
||||
To build the docs locally, see [the Nix development readme](/nix/README.md#documentation).
|
||||
|
||||
## Documentation structure
|
||||
|
||||
This documentation is structured according to tutorials-howtos-topics-references. For more details on the rationale of this structure,
|
||||
see https://www.divio.com/blog/documentation.
|
||||
|
||||
## Translating
|
||||
|
||||
To create `.po` files for translation into a new language pass the language code as the first argument to `postgrest-docs-build`.
|
||||
|
||||
Example to add German/de:
|
||||
|
||||
```
|
||||
postgrest-docs-build de
|
||||
```
|
||||
|
||||
The livereload server also supports a language/locale argument to show the translated docs during translation:
|
||||
|
||||
```
|
||||
postgrest-docs-serve de
|
||||
```
|
||||
|
||||
Spellcheck is currently only available for the default language.
|
||||
|
||||
@@ -5,38 +5,20 @@ The ER diagrams were created with https://github.com/BurntSushi/erd/.
|
||||
You can go download erd from https://github.com/BurntSushi/erd/releases and then do:
|
||||
|
||||
```bash
|
||||
./erd_static-x86-64 -i film.er -o ../_static/film.png
|
||||
./erd_static-x86-64 -i ./er/film.er -o ../_static/film.png
|
||||
```
|
||||
|
||||
The fonts used belong to the GNU FreeFont family. You can download them here: http://ftp.gnu.org/gnu/freefont/
|
||||
|
||||
## LaTeX
|
||||
## UML
|
||||
|
||||
The schema structure diagram is done with LaTeX. You can use a GUI like https://www.mathcha.io/editor to create the .tex file.
|
||||
The UML diagrams are created with https://plantuml.com/.
|
||||
|
||||
Then use this command to generate the png file.
|
||||
PlantUML only creates one diagram per file.
|
||||
That's why we need to create another one for dark mode.
|
||||
For example, for the file [uml/arch.uml](uml/arch.uml) there's [uml/dark/arch-dark.uml](uml/dark/arch-dark.uml) which includes the first one:
|
||||
|
||||
```bash
|
||||
pdflatex --shell-escape -halt-on-error db.tex
|
||||
|
||||
## and move it to the static folder(it's not easy to do it in one go with the pdflatex)
|
||||
mv db.png ../_static/
|
||||
```
|
||||
|
||||
LaTeX is used because it's a tweakable plain text format.
|
||||
|
||||
You can install the full latex suite with `nix`:
|
||||
|
||||
```
|
||||
nix-env -iA texlive.combined.scheme-full
|
||||
```
|
||||
|
||||
To tweak the file with a live reload environment use:
|
||||
|
||||
```bash
|
||||
# open the pdf(zathura used as an example)
|
||||
zathura db.pdf &
|
||||
|
||||
# live reload with entr
|
||||
echo db.tex | entr pdflatex --shell-escape -halt-on-error db.tex
|
||||
plantuml -tsvg uml/arch.uml -o ../../_static
|
||||
plantuml -tsvg -darkmode uml/dark/arch-dark.uml -o ../../../_static
|
||||
```
|
||||
|
||||
@@ -1,71 +0,0 @@
|
||||
\documentclass[convert]{standalone}
|
||||
\usepackage{amsmath}
|
||||
\usepackage{tikz}
|
||||
\usepackage{mathdots}
|
||||
\usepackage{yhmath}
|
||||
\usepackage{cancel}
|
||||
\usepackage{color}
|
||||
\usepackage{siunitx}
|
||||
\usepackage{array}
|
||||
\usepackage{multirow}
|
||||
\usepackage{amssymb}
|
||||
\usepackage{gensymb}
|
||||
\usepackage{tabularx}
|
||||
\usepackage{booktabs}
|
||||
\usetikzlibrary{fadings}
|
||||
\usetikzlibrary{patterns}
|
||||
\usetikzlibrary{shadows.blur}
|
||||
\usetikzlibrary{shapes}
|
||||
|
||||
\begin{document}
|
||||
|
||||
\newcommand\customScale{0.35}
|
||||
|
||||
\begin{tikzpicture}[x=0.75pt,y=0.75pt,yscale=-1,xscale=1, scale=\customScale, every node/.style={scale=\customScale}]
|
||||
|
||||
%Shape: Can [id:dp7234864758664346]
|
||||
\draw [fill={rgb, 255:red, 47; green, 97; blue, 144 } ,fill opacity=1 ] (497.5,51.5) -- (497.5,255.5) .. controls (497.5,275.66) and (423.18,292) .. (331.5,292) .. controls (239.82,292) and (165.5,275.66) .. (165.5,255.5) -- (165.5,51.5) .. controls (165.5,31.34) and (239.82,15) .. (331.5,15) .. controls (423.18,15) and (497.5,31.34) .. (497.5,51.5) .. controls (497.5,71.66) and (423.18,88) .. (331.5,88) .. controls (239.82,88) and (165.5,71.66) .. (165.5,51.5) ;
|
||||
%Shape: Rectangle [id:dp7384065579958246]
|
||||
\draw [fill={rgb, 255:red, 236; green, 227; blue, 227 } ,fill opacity=1 ] (189,115) -- (252.5,115) -- (252.5,155) -- (189,155) -- cycle ;
|
||||
%Shape: Rectangle [id:dp24763906430298177]
|
||||
\draw [fill={rgb, 255:red, 236; green, 227; blue, 227 } ,fill opacity=1 ] (292,118) -- (362,118) -- (362,158) -- (292,158) -- cycle ;
|
||||
%Shape: Rectangle [id:dp3775601612537265]
|
||||
\draw [fill={rgb, 255:red, 236; green, 227; blue, 227 } ,fill opacity=1 ] (397,114) -- (467,114) -- (467,154) -- (397,154) -- cycle ;
|
||||
%Shape: Rectangle [id:dp7071457022893852]
|
||||
\draw [fill={rgb, 255:red, 248; green, 231; blue, 28 } ,fill opacity=1 ] (269,199) -- (397.5,199) -- (397.5,273) -- (269,273) -- cycle ;
|
||||
%Straight Lines [id:da8846759047437789]
|
||||
\draw (268,234) -- (226.44,155.77) ;
|
||||
\draw [shift={(225.5,154)}, rotate = 422.02] [color={rgb, 255:red, 0; green, 0; blue, 0 } ][line width=0.75] (10.93,-3.29) .. controls (6.95,-1.4) and (3.31,-0.3) .. (0,0) .. controls (3.31,0.3) and (6.95,1.4) .. (10.93,3.29) ;
|
||||
%Straight Lines [id:da6908444738113828]
|
||||
\draw (309.5,198) -- (307.6,161) ;
|
||||
\draw [shift={(307.5,159)}, rotate = 447.06] [color={rgb, 255:red, 0; green, 0; blue, 0 } ][line width=0.75] (10.93,-3.29) .. controls (6.95,-1.4) and (3.31,-0.3) .. (0,0) .. controls (3.31,0.3) and (6.95,1.4) .. (10.93,3.29) ;
|
||||
%Straight Lines [id:da7168757864413169]
|
||||
\draw (398.5,233) -- (431.72,154.84) ;
|
||||
\draw [shift={(432.5,153)}, rotate = 473.03] [color={rgb, 255:red, 0; green, 0; blue, 0 } ][line width=0.75] (10.93,-3.29) .. controls (6.95,-1.4) and (3.31,-0.3) .. (0,0) .. controls (3.31,0.3) and (6.95,1.4) .. (10.93,3.29) ;
|
||||
%Up Down Arrow [id:dp14059754167108496]
|
||||
\draw [fill={rgb, 255:red, 126; green, 211; blue, 33 } ,fill opacity=1 ] (312.5,288.5) -- (330,273) -- (347.5,288.5) -- (338.75,288.5) -- (338.75,319.5) -- (347.5,319.5) -- (330,335) -- (312.5,319.5) -- (321.25,319.5) -- (321.25,288.5) -- cycle ;
|
||||
|
||||
% Text Node
|
||||
\draw (201,129) node [anchor=north west][inner sep=0.75pt] [align=left] {tables};
|
||||
% Text Node
|
||||
\draw (307,130) node [anchor=north west][inner sep=0.75pt] [align=left ] {tables};
|
||||
% Text Node
|
||||
\draw (414,127) node [anchor=north west][inner sep=0.75pt] [align=left] {tables};
|
||||
% Text Node
|
||||
\draw (272,203) node [anchor=north west][inner sep=0.75pt] [color={rgb, 255:red, 0; green, 0; blue, 0 } ,opacity=1 ] [align=center] { \\ views \\ + \\ \ \ stored procedures};
|
||||
|
||||
% Text Node
|
||||
\draw (322,178) node [anchor=north west][inner sep=0.75pt] [color={rgb, 255:red, 255; green, 255; blue, 255 } ,opacity=1 ] [align=left] {\large\textbf{api}};
|
||||
% Text Node
|
||||
\draw (190,97) node [anchor=north west][inner sep=0.75pt] [color={rgb, 255:red, 255; green, 255; blue, 255 } ,opacity=1 ] [align=left] {\large\textbf{internal}};
|
||||
% Text Node
|
||||
\draw (300,99) node [anchor=north west][inner sep=0.75pt] [color={rgb, 255:red, 255; green, 255; blue, 255 } ,opacity=1 ] [align=left] {\large\textbf{private}};
|
||||
% Text Node
|
||||
\draw (417,101) node [anchor=north west][inner sep=0.75pt] [color={rgb, 255:red, 255; green, 255; blue, 255 } ,opacity=1 ] [align=left] {\large\textbf{core}};
|
||||
% Text Node
|
||||
\draw (358,306) node [anchor=north west][inner sep=0.75pt] [align=left] {REST};
|
||||
|
||||
\end{tikzpicture}
|
||||
|
||||
|
||||
\end{document}
|
||||
@@ -0,0 +1,84 @@
|
||||
@startuml
|
||||
|
||||
skinparam backgroundColor transparent
|
||||
|
||||
package "PostgREST" {
|
||||
() HTTP as HTTPAPI
|
||||
HTTPAPI - [Auth]
|
||||
[Auth] -r.> [ApiRequest]
|
||||
[ApiRequest] -r.> [Plan]
|
||||
[Plan] -r.> [Query]
|
||||
[Query] - () "Connection Pool" : "\t"
|
||||
[Plan] -u-> [Schema Cache]:uses
|
||||
[Schema Cache] <- () Listener : reloads
|
||||
|
||||
() HTTP as HTTPADMIN
|
||||
[Admin] -r- () HTTPADMIN
|
||||
[Config] -l- () CLI
|
||||
|
||||
[Config] <-r~ Listener
|
||||
|
||||
HTTPADMIN -[hidden]r- CLI
|
||||
[Schema Cache] -l[hidden]- [Config]
|
||||
[Schema Cache] -l[hidden]- [Admin]
|
||||
[Schema Cache] -l[hidden]- CLI
|
||||
}
|
||||
|
||||
|
||||
database "PostgreSQL" {
|
||||
node Authorization {
|
||||
rectangle "Roles, GRANT, RLS"
|
||||
}
|
||||
node "API schema" as API {
|
||||
rectangle "Functions, Views"
|
||||
}
|
||||
rectangle "Tables, extensions" as tbs
|
||||
API -d- tbs
|
||||
|
||||
API -l[hidden]- Authorization
|
||||
}
|
||||
|
||||
:user:
|
||||
hexagon Proxy
|
||||
:user: .r-> Proxy
|
||||
HTTPAPI <.l- Proxy
|
||||
|
||||
:operator: .d-> HTTPADMIN
|
||||
:operator: .d-> CLI
|
||||
|
||||
|
||||
PostgreSQL <.developer : "\t"
|
||||
Listener -r.> "PostgreSQL"
|
||||
"Connection Pool" -r.> "PostgreSQL" : "\t\t"
|
||||
|
||||
|
||||
note bottom of Auth
|
||||
Authenticates the user request
|
||||
end note
|
||||
|
||||
note bottom of ApiRequest
|
||||
Parses the URL syntax
|
||||
end note
|
||||
|
||||
note bottom of Query
|
||||
Generates the SQL
|
||||
end note
|
||||
|
||||
note top of Listener
|
||||
LISTEN session
|
||||
end note
|
||||
|
||||
url of Admin is [[../references/admin_server.html#admin-server]]
|
||||
url of API is [[../explanations/schema_isolation.html]]
|
||||
url of Auth is [[../references/auth.html#authn]]
|
||||
url of Authorization is [[../explanations/db_authz.html]]
|
||||
url of CLI is [[../references/cli.html#cli]]
|
||||
url of "Connection Pool" is [[../references/connection_pool.html]]
|
||||
url of Config is [[../references/configuration.html#configuration]]
|
||||
url of HTTPADMIN is [[https://aosabook.org/en/posa/warp.html]]
|
||||
url of HTTPAPI is [[https://aosabook.org/en/posa/warp.html]]
|
||||
url of Listener is [[../references/listener.html#listener]]
|
||||
url of Proxy is [[../explanations/nginx.html]]
|
||||
url of "Schema Cache" is [[../references/schema_cache.html#schema-cache]]
|
||||
|
||||
@enduml
|
||||
@@ -0,0 +1,3 @@
|
||||
@startuml
|
||||
!include ../arch.uml
|
||||
@enduml
|
||||
@@ -0,0 +1,3 @@
|
||||
@startuml
|
||||
!include ../sch-iso.uml
|
||||
@enduml
|
||||
@@ -0,0 +1,29 @@
|
||||
@startuml
|
||||
|
||||
skinparam backgroundColor transparent
|
||||
skinparam linetype ortho
|
||||
|
||||
skinparam node {
|
||||
backgroundColor transparent
|
||||
borderThickness 1
|
||||
}
|
||||
|
||||
database "PostgreSQL" {
|
||||
node public {
|
||||
rectangle tables_public as "tables"
|
||||
}
|
||||
|
||||
node extensions as "**extensions**" {
|
||||
}
|
||||
|
||||
node API as "<size:20>api" {
|
||||
rectangle vf_api as "views + functions"
|
||||
}
|
||||
|
||||
tables_public <-- vf_api
|
||||
extensions <-- vf_api
|
||||
}
|
||||
|
||||
vf_api <-[thickness=3]-> () PostgREST
|
||||
|
||||
@enduml
|
||||
|
Before Width: | Height: | Size: 88 KiB |
|
After Width: | Height: | Size: 23 KiB |
|
After Width: | Height: | Size: 24 KiB |
@@ -28,6 +28,7 @@ div.line-block {
|
||||
|
||||
#sponsors img{
|
||||
margin: 10px;
|
||||
width: 13em; /* ".. image::" does not apply width properly to SVGs */
|
||||
}
|
||||
|
||||
#thanks{
|
||||
@@ -93,3 +94,62 @@ div.line-block {
|
||||
#api span.caption-text {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* Tweaks for dark mode from extension: sphinx-rtd-dark-theme */
|
||||
|
||||
html[data-theme="dark"] .highlight {
|
||||
background-color: #17181c !important;
|
||||
}
|
||||
|
||||
html[data-theme="dark"] .sphinx-tabs-tab {
|
||||
color: var(--dark-link-color);
|
||||
}
|
||||
|
||||
html[data-theme="dark"] .sphinx-tabs-panel {
|
||||
border: 1px solid #404040;
|
||||
border-top: 0;
|
||||
background: #141414;
|
||||
}
|
||||
|
||||
html[data-theme="dark"] .sphinx-tabs-tab[aria-selected="true"] {
|
||||
border: 1px solid #404040;
|
||||
border-bottom: 1px solid #141414;
|
||||
background-color: #141414;
|
||||
}
|
||||
|
||||
html[data-theme="dark"] [role="tablist"] {
|
||||
border-bottom: 1px solid #404040;
|
||||
}
|
||||
|
||||
html[data-theme="dark"] .btn-neutral {
|
||||
color: white !important;
|
||||
}
|
||||
|
||||
html[data-theme="dark"] .img-dark {
|
||||
display: inline;
|
||||
}
|
||||
|
||||
html:not([data-theme="dark"]) .img-dark {
|
||||
display: none;
|
||||
}
|
||||
|
||||
html[data-theme="dark"] .img-light {
|
||||
display: none;
|
||||
}
|
||||
|
||||
html:not([data-theme="dark"]) .img-light {
|
||||
display: inline;
|
||||
}
|
||||
|
||||
html[data-theme="dark"] .img-translucent img {
|
||||
background-color: #cccccc;
|
||||
}
|
||||
|
||||
.img-translucent img {
|
||||
transition: background-color 0.3s;
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.svg-container-md {
|
||||
max-width: 400px;
|
||||
}
|
||||
|
||||
|
Before Width: | Height: | Size: 345 KiB |
|
Before Width: | Height: | Size: 15 KiB |
|
Before Width: | Height: | Size: 9.0 KiB |
|
Before Width: | Height: | Size: 9.1 KiB |
|
After Width: | Height: | Size: 142 KiB |
|
After Width: | Height: | Size: 89 KiB |
|
After Width: | Height: | Size: 41 KiB |
|
After Width: | Height: | Size: 6.3 KiB |
|
Before Width: | Height: | Size: 27 KiB |
|
Before Width: | Height: | Size: 62 KiB |
@@ -0,0 +1 @@
|
||||
<?xml version="1.0" encoding="us-ascii" standalone="no"?><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" contentStyleType="text/css" height="411px" preserveAspectRatio="none" style="width:315px;height:411px;" version="1.1" viewBox="0 0 315 411" width="315px" zoomAndPan="magnify"><defs/><g><!--cluster PostgreSQL--><g id="cluster_PostgreSQL"><path d="M6,16 C6,6 152,6 152,6 C152,6 298,6 298,16 L298,309.14 C298,319.14 152,319.14 152,319.14 C152,319.14 6,319.14 6,309.14 L6,16 " fill="none" style="stroke:#E7E7E7;stroke-width:1.0;"/><path d="M6,16 C6,26 152,26 152,26 C152,26 298,26 298,16 " fill="none" style="stroke:#E7E7E7;stroke-width:1.0;"/><text fill="#FFFFFF" font-family="sans-serif" font-size="14" font-weight="bold" lengthAdjust="spacing" textLength="81.375" x="111.3125" y="42.9659">PostgreSQL</text></g><!--cluster public--><g id="cluster_public"><polygon fill="none" points="30,77,40,67,150,67,150,155.07,140,165.07,30,165.07,30,77" style="stroke:#E7E7E7;stroke-width:1.0;"/><line style="stroke:#E7E7E7;stroke-width:1.0;" x1="140" x2="150" y1="77" y2="67"/><line style="stroke:#E7E7E7;stroke-width:1.0;" x1="30" x2="140" y1="77" y2="77"/><line style="stroke:#E7E7E7;stroke-width:1.0;" x1="140" x2="140" y1="77" y2="165.07"/><text fill="#FFFFFF" font-family="sans-serif" font-size="14" font-weight="bold" lengthAdjust="spacing" textLength="44.625" x="63.6875" y="94.9659">public</text></g><!--cluster API--><g id="cluster_API"><polygon fill="none" points="68,199.07,78,189.07,236,189.07,236,285.14,226,295.14,68,295.14,68,199.07" style="stroke:#E7E7E7;stroke-width:1.0;"/><line style="stroke:#E7E7E7;stroke-width:1.0;" x1="226" x2="236" y1="199.07" y2="189.07"/><line style="stroke:#E7E7E7;stroke-width:1.0;" x1="68" x2="226" y1="199.07" y2="199.07"/><line style="stroke:#E7E7E7;stroke-width:1.0;" x1="226" x2="226" y1="199.07" y2="295.14"/><text fill="#FFFFFF" font-family="sans-serif" font-size="20" font-weight="bold" lengthAdjust="spacing" textLength="29.875" x="133.0625" y="223.45">api</text></g><!--entity tables_public--><g id="elem_tables_public"><rect fill="#313139" height="39.0679" rx="2.5" ry="2.5" style="stroke:#E7E7E7;stroke-width:0.5;" width="61" x="69.5" y="110"/><text fill="#FFFFFF" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="41" x="79.5" y="134.9659">tables</text></g><!--entity extensions--><g id="elem_extensions"><polygon fill="none" points="165.81,115,175.81,105,282.185,105,282.185,144.0679,272.185,154.0679,165.81,154.0679,165.81,115" style="stroke:#E7E7E7;stroke-width:1.0;"/><line style="stroke:#E7E7E7;stroke-width:1.0;" x1="272.185" x2="282.185" y1="115" y2="105"/><line style="stroke:#E7E7E7;stroke-width:1.0;" x1="165.81" x2="272.185" y1="115" y2="115"/><line style="stroke:#E7E7E7;stroke-width:1.0;" x1="272.185" x2="272.185" y1="115" y2="154.0679"/><text fill="#FFFFFF" font-family="sans-serif" font-size="14" font-weight="bold" lengthAdjust="spacing" textLength="76.375" x="180.81" y="139.9659">extensions</text></g><!--entity vf_api--><g id="elem_vf_api"><rect fill="#313139" height="39.0679" rx="2.5" ry="2.5" style="stroke:#E7E7E7;stroke-width:0.5;" width="136" x="84" y="240.07"/><text fill="#FFFFFF" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="116" x="94" y="265.0359">views + functions</text></g><!--entity PostgREST--><g id="elem_PostgREST"><ellipse cx="152" cy="371.14" fill="#313139" rx="8" ry="8" style="stroke:#E7E7E7;stroke-width:0.5;"/><text fill="#FFFFFF" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="70" x="117" y="403.1059">PostgREST</text></g><!--reverse link tables_public to vf_api--><g id="link_tables_public_vf_api"><path d="M107.25,155.29 C107.25,179.74 107.25,215.13 107.25,239.67 " fill="none" id="tables_public-backto-vf_api" style="stroke:#E7E7E7;stroke-width:1.0;"/><polygon fill="#E7E7E7" points="107.25,149.29,103.25,158.29,107.25,154.29,111.25,158.29,107.25,149.29" style="stroke:#E7E7E7;stroke-width:1.0;"/></g><!--reverse link extensions to vf_api--><g id="link_extensions_vf_api"><path d="M192.91,160.31 C192.91,185.07 192.91,216.68 192.91,239.61 " fill="none" id="extensions-backto-vf_api" style="stroke:#E7E7E7;stroke-width:1.0;"/><polygon fill="#E7E7E7" points="192.91,154.31,188.91,163.31,192.91,159.31,196.91,163.31,192.91,154.31" style="stroke:#E7E7E7;stroke-width:1.0;"/></g><!--link vf_api to PostgREST--><g id="link_vf_api_PostgREST"><path d="M152,285.55 C152,309.98 152,338.34 152,356.18 " fill="none" id="vf_api-PostgREST" style="stroke:#E7E7E7;stroke-width:3.0;"/><polygon fill="#E7E7E7" points="152,279.55,148,288.55,152,284.55,156,288.55,152,279.55" style="stroke:#E7E7E7;stroke-width:3.0;"/><polygon fill="#E7E7E7" points="152,362.18,156,353.18,152,357.18,148,353.18,152,362.18" style="stroke:#E7E7E7;stroke-width:3.0;"/></g><!--SRC=[KypCIyufJKbLqDFJBqxEqCqipjShpSq10000]--></g></svg>
|
||||
|
After Width: | Height: | Size: 4.8 KiB |
|
After Width: | Height: | Size: 5.1 KiB |
|
Before Width: | Height: | Size: 4.4 KiB |
|
Before Width: | Height: | Size: 89 KiB |
@@ -28,7 +28,12 @@ import os
|
||||
# Add any Sphinx extension module names here, as strings. They can be
|
||||
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
|
||||
# ones.
|
||||
extensions = ["sphinx_tabs.tabs", "sphinx_copybutton"]
|
||||
extensions = [
|
||||
"sphinx_tabs.tabs",
|
||||
"sphinx_copybutton",
|
||||
"sphinxext.opengraph",
|
||||
"sphinx_rtd_dark_mode",
|
||||
]
|
||||
|
||||
# Add any paths that contain templates here, relative to this directory.
|
||||
templates_path = ["_templates"]
|
||||
@@ -45,7 +50,7 @@ source_suffix = ".rst"
|
||||
master_doc = "index"
|
||||
|
||||
# This is overriden by readthedocs with the version tag anyway
|
||||
version = "11.2"
|
||||
version = "12.2"
|
||||
# To avoid repetition in <title> we set this to an empty string.
|
||||
release = ""
|
||||
|
||||
@@ -59,7 +64,7 @@ copyright = "2017, " + author
|
||||
#
|
||||
# This is also used if you do content translation via gettext catalogs.
|
||||
# Usually you set "language" from the command line for these cases.
|
||||
language = None
|
||||
language = "en"
|
||||
|
||||
# There are two options for replacing |today|: either, you set today to some
|
||||
# non-false value, then it is used:
|
||||
@@ -70,7 +75,7 @@ language = None
|
||||
# List of patterns, relative to source directory, that match files and
|
||||
# directories to ignore when looking for source files.
|
||||
# This patterns also effect to html_static_path and html_extra_path
|
||||
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]
|
||||
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store", "shared/*.rst"]
|
||||
|
||||
# The reST default role (used for this markup: `text`) to use for all
|
||||
# documents.
|
||||
@@ -287,7 +292,28 @@ def setup(app):
|
||||
app.add_css_file("css/custom.css")
|
||||
|
||||
|
||||
user_agent = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:135.0) Gecko/20100101 Firefox/135.0"
|
||||
# taken from https://github.com/sphinx-doc/sphinx/blob/82dad44e5bd3776ecb6fd8ded656bc8151d0e63d/sphinx/util/requests.py#L42
|
||||
user_agent = "Mozilla/5.0 (X11; Linux x86_64; rv:25.0) Gecko/20100101 Firefox/25.0"
|
||||
|
||||
linkcheck_ignore = [
|
||||
r"https://www.patreon.com/postgrest",
|
||||
r"https://blog.frankel.ch/poor-man-api",
|
||||
]
|
||||
|
||||
# sphinx-tabs configuration
|
||||
sphinx_tabs_disable_tab_closing = True
|
||||
|
||||
# sphinx_rtd_dark_mode configuration
|
||||
default_dark_mode = False
|
||||
|
||||
# sphinxext-opengraph configuration
|
||||
|
||||
ogp_image = "_images/logo.png"
|
||||
ogp_use_first_image = True
|
||||
ogp_enable_meta_description = True
|
||||
ogp_description_length = 300
|
||||
|
||||
## RTD sets html_baseurl, ensures we use the correct env for canonical URLs
|
||||
## Useful to generate correct meta tags for Open Graph
|
||||
## Refs: https://github.com/readthedocs/readthedocs.org/issues/10226, https://github.com/urllib3/urllib3/pull/3064
|
||||
html_baseurl = os.environ.get("READTHEDOCS_CANONICAL_URL", "/")
|
||||
|
||||
@@ -1,93 +0,0 @@
|
||||
let
|
||||
# Commit of the Nixpkgs repository that we want to use.
|
||||
nixpkgsVersion = {
|
||||
date = "2021-06-02";
|
||||
rev = "84aa23742f6c72501f9cc209f29c438766f5352d";
|
||||
tarballHash = "0h7xl6q0yjrbl9vm3h6lkxw692nm8bg3wy65gm95a2mivhrdjpxp";
|
||||
};
|
||||
|
||||
# Nix files that describe the Nixpkgs repository. We evaluate the expression
|
||||
# using `import` below.
|
||||
pkgs = import
|
||||
(fetchTarball {
|
||||
url = "https://github.com/nixos/nixpkgs/archive/${nixpkgsVersion.rev}.tar.gz";
|
||||
sha256 = nixpkgsVersion.tarballHash;
|
||||
})
|
||||
{ };
|
||||
|
||||
sphinxTabsPkg = ps: ps.callPackage ./extensions/sphinx-tabs.nix { };
|
||||
sphinxCopybuttonPkg = ps: ps.callPackage ./extensions/sphinx-copybutton.nix { };
|
||||
|
||||
python = pkgs.python3.withPackages (ps: [ ps.sphinx ps.sphinx_rtd_theme ps.livereload (sphinxTabsPkg ps) (sphinxCopybuttonPkg ps) ]);
|
||||
in
|
||||
{
|
||||
inherit pkgs;
|
||||
|
||||
build =
|
||||
pkgs.writeShellScriptBin "postgrest-docs-build"
|
||||
''
|
||||
set -euo pipefail
|
||||
cd "$(${pkgs.git}/bin/git rev-parse --show-toplevel)/docs"
|
||||
|
||||
# clean previous build, otherwise some errors might be supressed
|
||||
rm -rf _build
|
||||
|
||||
${python}/bin/sphinx-build --color -W -b html -a -n . _build
|
||||
'';
|
||||
|
||||
serve =
|
||||
pkgs.writeShellScriptBin "postgrest-docs-serve"
|
||||
''
|
||||
set -euo pipefail
|
||||
cd "$(${pkgs.git}/bin/git rev-parse --show-toplevel)/docs"
|
||||
|
||||
# livereload_docs.py needs to find "sphinx-build"
|
||||
PATH=${python}/bin:$PATH
|
||||
|
||||
${python}/bin/python livereload_docs.py
|
||||
'';
|
||||
|
||||
spellcheck =
|
||||
pkgs.writeShellScriptBin "postgrest-docs-spellcheck"
|
||||
''
|
||||
set -euo pipefail
|
||||
cd "$(${pkgs.git}/bin/git rev-parse --show-toplevel)/docs"
|
||||
|
||||
FILES=$(find . -type f -iname '*.rst' | tr '\n' ' ')
|
||||
|
||||
cat $FILES \
|
||||
| grep -v '^\(\.\.\| \)' \
|
||||
| sed 's/`.*`//g' \
|
||||
| ${pkgs.aspell}/bin/aspell -d ${pkgs.aspellDicts.en}/lib/aspell/en_US -p ./postgrest.dict list \
|
||||
| sort -f \
|
||||
| tee misspellings
|
||||
test ! -s misspellings
|
||||
'';
|
||||
|
||||
# dictcheck detects obsolete entries in postgrest.dict, that are not used anymore
|
||||
dictcheck =
|
||||
pkgs.writeShellScriptBin "postgrest-docs-dictcheck"
|
||||
''
|
||||
set -euo pipefail
|
||||
cd "$(${pkgs.git}/bin/git rev-parse --show-toplevel)/docs"
|
||||
|
||||
FILES=$(find . -type f -iname '*.rst' | tr '\n' ' ')
|
||||
|
||||
cat postgrest.dict \
|
||||
| tail -n+2 \
|
||||
| tr '\n' '\0' \
|
||||
| xargs -0 -n 1 -i \
|
||||
sh -c "grep \"{}\" $FILES > /dev/null || echo \"{}\"" \
|
||||
| tee unuseddict
|
||||
test ! -s unuseddict
|
||||
'';
|
||||
|
||||
linkcheck =
|
||||
pkgs.writeShellScriptBin "postgrest-docs-linkcheck"
|
||||
''
|
||||
set -euo pipefail
|
||||
cd "$(${pkgs.git}/bin/git rev-parse --show-toplevel)/docs"
|
||||
|
||||
${python}/bin/sphinx-build --color -b linkcheck . _build
|
||||
'';
|
||||
}
|
||||
@@ -6,10 +6,10 @@ Community Tutorials
|
||||
* `Building a Contacts List with PostgREST and Vue.js <https://www.youtube.com/watch?v=iHtsALtD5-U>`_ -
|
||||
In this video series, DigitalOcean shows how to build and deploy an Nginx + PostgREST(using a managed PostgreSQL database) + Vue.js webapp in an Ubuntu server droplet.
|
||||
|
||||
* `PostgREST + Auth0: Create REST API in minutes, and add social login using Auth0 <https://samkhawase.com/blog/postgrest-1-introduction/>`_ - A step-by-step tutorial to show how to dockerize and integrate Auth0 to PostgREST service.
|
||||
* `PostgREST + Auth0: Create REST API in mintutes, and add social login using Auth0 <https://samkhawase.com/blog/postgrest/>`_ - A step-by-step tutorial to show how to dockerize and integrate Auth0 to PostgREST service.
|
||||
|
||||
* `PostgREST + PostGIS API tutorial in 5 minutes <https://gis-ops.com/postgrest-postgis-api-tutorial-geospatial-api-in-5-minutes/>`_ -
|
||||
In this tutorial, GIS • OPS shows how to perform PostGIS calculations through PostgREST :ref:`s_procs` interface.
|
||||
In this tutorial, GIS • OPS shows how to perform PostGIS calculations through PostgREST :ref:`functions` interface.
|
||||
|
||||
* `"CodeLess" backend using postgres, postgrest and oauth2 authentication with keycloak <https://www.mathieupassenaud.fr/codeless_backend/>`_ -
|
||||
A step-by-step tutorial for using PostgREST with KeyCloak(hosted on a managed service).
|
||||
@@ -22,6 +22,8 @@ Community Tutorials
|
||||
|
||||
* `A poor man's API <https://blog.frankel.ch/poor-man-api>`_ - Shows how to integrate PostgREST with Apache APISIX as an alternative to Nginx.
|
||||
|
||||
.. * `Accessing a PostgreSQL database in Godot 4 via PostgREST <https://peterkingsbury.com/2022/08/16/godot-postgresql-postgrest/>`_
|
||||
|
||||
.. _templates:
|
||||
|
||||
Templates
|
||||
@@ -49,17 +51,18 @@ DevOps
|
||||
|
||||
* `cloudgov-demo-postgrest <https://github.com/GSA/cloudgov-demo-postgrest>`_ - demo for a federally-compliant REST API on cloud.gov
|
||||
* `cloudstark/helm-charts <https://github.com/cloudstark/helm-charts/tree/master/postgrest>`_ - helm chart to deploy PostgREST to a Kubernetes cluster via a Deployment and Service
|
||||
* `jbkarle/postgrest <https://github.com/jbkarle/postgrest>`_ - helm chart with a demo database for development and test purposes
|
||||
* `Limezest/postgrest-cloud-run <https://github.com/Limezest/postgrest-cloud-run>`_ - expose a PostgreSQL database on Cloud SQL using Cloud Run
|
||||
* `cyril-sabourault/postgrest-cloud-run <https://github.com/cyril-sabourault/postgrest-cloud-run>`_ - expose a PostgreSQL database on Cloud SQL using Cloud Run
|
||||
* `eyberg/postgrest <https://repo.ops.city/v2/packages/eyberg/postgrest/10.1.1/x86_64/show>`_ - run PostgREST as a Nanos unikernel
|
||||
* `jbkarle/postgrest <https://github.com/jbkarle/postgrest>`_ - helm chart with a demo database for development and test purposes
|
||||
|
||||
.. _eco_external_notification:
|
||||
|
||||
External Notification
|
||||
---------------------
|
||||
|
||||
These are PostgreSQL bridges that propagate LISTEN/NOTIFY to external queues for further processing. This allows stored procedures to initiate actions outside the database such as sending emails.
|
||||
These are PostgreSQL bridges that propagate LISTEN/NOTIFY to external queues for further processing. This allows functions to initiate actions outside the database such as sending emails.
|
||||
|
||||
* `pg-notify-stdout <https://github.com/mkleczek/pg-notify-stdout>`_ - writes notifications to standard output (use in shell scripts etc.)
|
||||
* `pg-notify-webhook <https://github.com/vbalasu/pg-notify-webhook>`_ - trigger webhooks from PostgreSQL's LISTEN/NOTIFY
|
||||
* `pgsql-listen-exchange <https://github.com/gmr/pgsql-listen-exchange>`_ - RabbitMQ
|
||||
* `postgres-websockets <https://github.com/diogob/postgres-websockets>`_ - expose web sockets for PostgreSQL's LISTEN/NOTIFY
|
||||
@@ -82,12 +85,12 @@ Client-Side Libraries
|
||||
---------------------
|
||||
|
||||
* `postgrest-csharp <https://github.com/supabase-community/postgrest-csharp>`_ - C#
|
||||
* `postgrest-dart <https://github.com/supabase-community/postgrest-dart>`_ - Dart
|
||||
* `postgrest-ex <https://github.com/J0/postgrest-ex>`_ - Elixir
|
||||
* `postgrest-dart <https://github.com/supabase/postgrest-dart>`_ - Dart
|
||||
* `postgrest-ex <https://github.com/supabase-community/postgrest-ex>`_ - Elixir
|
||||
* `postgrest-go <https://github.com/supabase-community/postgrest-go>`_ - Go
|
||||
* `postgrest-js <https://github.com/supabase/postgrest-js>`_ - TypeScript/JavaScript
|
||||
* `postgrest-kt <https://github.com/supabase-community/postgrest-kt>`_ - Kotlin
|
||||
* `postgrest-py <https://github.com/supabase/postgrest-py>`_ - Python
|
||||
* `postgrest-py <https://github.com/supabase-community/postgrest-py>`_ - Python
|
||||
* `postgrest-rs <https://github.com/supabase-community/postgrest-rs>`_ - Rust
|
||||
* `postgrest-swift <https://github.com/supabase-community/postgrest-swift>`_ - Swift
|
||||
* `redux-postgrest <https://github.com/andytango/redux-postgrest>`_ - TypeScript/JS, client integrated with (React) Redux.
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
Architecture
|
||||
############
|
||||
|
||||
This page describes the architecture of PostgREST.
|
||||
|
||||
Bird's Eye View
|
||||
===============
|
||||
|
||||
You can click on the components to navigate to their respective documentation.
|
||||
|
||||
.. container:: img-dark
|
||||
|
||||
.. See https://github.com/sphinx-doc/sphinx/issues/2240#issuecomment-187366626
|
||||
|
||||
.. raw:: html
|
||||
|
||||
<object width="100%" data="../_static/arch-dark.svg" type="image/svg+xml"></object>
|
||||
|
||||
.. container:: img-light
|
||||
|
||||
.. raw:: html
|
||||
|
||||
<object width="100%" data="../_static/arch.svg" type="image/svg+xml"></object>
|
||||
|
||||
|
||||
Code Map
|
||||
========
|
||||
|
||||
This section talks briefly about various important modules.
|
||||
|
||||
Main
|
||||
----
|
||||
|
||||
The starting point of the program is `Main.hs <https://github.com/PostgREST/postgrest/blob/main/main/Main.hs>`_.
|
||||
|
||||
CLI
|
||||
---
|
||||
|
||||
Main then calls `CLI.hs <https://github.com/PostgREST/postgrest/blob/main/src/PostgREST/CLI.hs>`_, which is in charge of :ref:`cli`.
|
||||
|
||||
App
|
||||
---
|
||||
|
||||
`App.hs <https://github.com/PostgREST/postgrest/blob/main/src/PostgREST/App.hs>`_ is then in charge of composing the different modules.
|
||||
|
||||
Auth
|
||||
----
|
||||
|
||||
`Auth.hs <https://github.com/PostgREST/postgrest/blob/main/src/PostgREST/Auth.hs>`_ is in charge of :ref:`authn`.
|
||||
|
||||
Api Request
|
||||
-----------
|
||||
|
||||
`ApiRequest.hs <https://github.com/PostgREST/postgrest/blob/main/src/PostgREST/ApiRequest.hs>`_ is in charge of parsing the URL query string (following PostgREST syntax), the request headers, and the request body.
|
||||
|
||||
A request might be rejected at this level if it's invalid. For example when providing an unknown media type to PostgREST or using an unknown HTTP method.
|
||||
|
||||
Plan
|
||||
----
|
||||
|
||||
Using the Schema Cache, `Plan.hs <https://github.com/PostgREST/postgrest/blob/main/src/PostgREST/Plan.hs>`_ fills in out-of-band SQL details (like an ``ON CONFLICT (pk)`` clause) required to complete the user request.
|
||||
|
||||
A request might be rejected at this level if it's invalid. For example when doing resource embedding on a nonexistent resource.
|
||||
|
||||
Query
|
||||
-----
|
||||
|
||||
`Query.hs <https://github.com/PostgREST/postgrest/blob/main/src/PostgREST/Query.hs>`_ generates the SQL queries (parametrized and prepared) required to satisfy the user request.
|
||||
|
||||
Only at this stage a connection from the pool might be used.
|
||||
|
||||
Schema Cache
|
||||
------------
|
||||
|
||||
`SchemaCache.hs <https://github.com/PostgREST/postgrest/blob/main/src/PostgREST/SchemaCache.hs>`_ is in charge of :ref:`schema_cache`.
|
||||
|
||||
Config
|
||||
------
|
||||
|
||||
`Config.hs <https://github.com/PostgREST/postgrest/blob/main/src/PostgREST/Config.hs>`_ is in charge of :ref:`configuration`.
|
||||
|
||||
Admin
|
||||
-----
|
||||
|
||||
`Admin.hs <https://github.com/PostgREST/postgrest/blob/main/src/PostgREST/Admin.hs>`_ is in charge of the :ref:`admin_server`.
|
||||
|
||||
HTTP
|
||||
----
|
||||
|
||||
The HTTP server is provided by `Warp <https://aosabook.org/en/posa/warp.html>`_.
|
||||
|
||||
Listener
|
||||
--------
|
||||
|
||||
`Listener.hs <https://github.com/PostgREST/postgrest/blob/main/src/PostgREST/Listener.hs>`_ is in charge of the :ref:`listener`.
|
||||
@@ -15,7 +15,7 @@ Roles for Each Web User
|
||||
|
||||
PostgREST can accommodate either viewpoint. If you treat a role as a single user then the :ref:`jwt_impersonation` does most of what you need. When an authenticated user makes a request PostgREST will switch into the database role for that user, which in addition to restricting queries, is available to SQL through the :code:`current_user` variable.
|
||||
|
||||
You can use row-level security to flexibly restrict visibility and access for the current user. Here is an `example <https://www.enterprisedb.com:443/blog/application-users-vs-row-level-security>`_ from Tomas Vondra, a chat table storing messages sent between users. Users can insert rows into it to send messages to other users, and query it to see messages sent to them by other users.
|
||||
You can use row-level security to flexibly restrict visibility and access for the current user. Here is an `example <https://www.2ndquadrant.com/en/blog/application-users-vs-row-level-security/>`_ from Tomas Vondra, a chat table storing messages sent between users. Users can insert rows into it to send messages to other users, and query it to see messages sent to them by other users.
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
@@ -92,19 +92,10 @@ You can mix the group and individual role policies. For instance we could still
|
||||
-- allow authenticator to switch into user000 role
|
||||
-- (the role itself has nologin)
|
||||
|
||||
.. _schema_isolation:
|
||||
|
||||
Schemas
|
||||
=======
|
||||
|
||||
A PostgREST instance exposes all the tables, views, and stored procedures of the schemas configured in :ref:`db-schemas`. This means private data or implementation details can go inside private schemas and be invisible to HTTP clients.
|
||||
|
||||
It is recommended that you don't expose tables on the schemas you expose, instead expose views and stored procedures which insulate the internal details from the outside world.
|
||||
This allows you to change the internals of your schema and maintain backwards compatibility. It also keeps your code easier to refactor, and provides a natural way to do API versioning.
|
||||
|
||||
.. image:: ../_static/db.png
|
||||
|
||||
You must explicitly allow roles to access the exposed schemas:
|
||||
You must explicitly allow roles to access the exposed schemas in :ref:`db-schemas`.
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
@@ -165,7 +156,7 @@ You can also grant execute on all functions in a schema to a higher privileged r
|
||||
Security definer
|
||||
----------------
|
||||
|
||||
A function is executed with the privileges of the user who calls it. This means that the user has to have all permissions to do the operations the procedure performs.
|
||||
A function is executed with the privileges of the user who calls it. This means that the user has to have all permissions to do the operations the function performs.
|
||||
If the function accesses private database objects, your :ref:`API roles <roles>` won't be able to successfully execute the function.
|
||||
|
||||
Another option is to define the function with the :code:`SECURITY DEFINER` option. Then only one permission check will take place, the permission to call the function, and the operations in the function will have the authority of the user who owns the function itself.
|
||||
@@ -175,7 +166,7 @@ Another option is to define the function with the :code:`SECURITY DEFINER` optio
|
||||
-- login as a user wich has privileges on the private schemas
|
||||
|
||||
-- create a sample function
|
||||
create or replace function login(email text, pass text) returns jwt_token as $$
|
||||
create or replace function login(email text, pass text, out token text) as $$
|
||||
begin
|
||||
-- access to a private schema called 'auth'
|
||||
select auth.user_role(email, pass) into _role;
|
||||
@@ -189,7 +180,7 @@ Note the ``SECURITY DEFINER`` keywords at the end of the function. See `PostgreS
|
||||
Views
|
||||
=====
|
||||
|
||||
Views are invoked with the privileges of the view owner, much like stored procedures with the ``SECURITY DEFINER`` option. When created by a SUPERUSER role, all `row-level security <https://www.postgresql.org/docs/current/ddl-rowsecurity.html>`_ policies will be bypassed.
|
||||
Views are invoked with the privileges of the view owner, much like functions with the ``SECURITY DEFINER`` option. When created by a SUPERUSER role, all `row-level security <https://www.postgresql.org/docs/current/ddl-rowsecurity.html>`_ policies will be bypassed.
|
||||
|
||||
If you're on PostgreSQL >= 15, this behavior can be changed by specifying the ``security_invoker`` option.
|
||||
|
||||
|
||||
@@ -3,58 +3,12 @@
|
||||
Installation
|
||||
############
|
||||
|
||||
The release page has `pre-compiled binaries for Mac OS X, Windows, Linux and FreeBSD <https://github.com/PostgREST/postgrest/releases/latest>`_ .
|
||||
The release page has `pre-compiled binaries for macOS, Windows, Linux and FreeBSD <https://github.com/PostgREST/postgrest/releases/latest>`_.
|
||||
The Linux binary is a static executable that can be run on any Linux distribution.
|
||||
|
||||
You can also use your OS package manager.
|
||||
|
||||
.. tabs::
|
||||
|
||||
.. group-tab:: Mac OSX
|
||||
|
||||
You can install PostgREST from the `Homebrew official repo <https://formulae.brew.sh/formula/postgrest>`_.
|
||||
|
||||
.. code:: bash
|
||||
|
||||
brew install postgrest
|
||||
|
||||
.. group-tab:: FreeBSD
|
||||
|
||||
You can install PostgREST from the `official ports <https://www.freshports.org/www/hs-postgrest>`_.
|
||||
|
||||
.. code:: bash
|
||||
|
||||
pkg install hs-postgrest
|
||||
|
||||
.. group-tab:: Linux
|
||||
|
||||
.. tabs::
|
||||
|
||||
.. tab:: Arch Linux
|
||||
|
||||
You can install PostgREST from the `community repo <https://archlinux.org/packages/extra/x86_64/postgrest/>`_.
|
||||
|
||||
.. code:: bash
|
||||
|
||||
pacman -S postgrest
|
||||
|
||||
.. tab:: Nix
|
||||
|
||||
You can install PostgREST from nixpkgs.
|
||||
|
||||
.. code:: bash
|
||||
|
||||
nix-env -i haskellPackages.postgrest
|
||||
|
||||
.. group-tab:: Windows
|
||||
|
||||
You can install PostgREST using `Chocolatey <https://community.chocolatey.org/packages/postgrest>`_ or `Scoop <https://github.com/ScoopInstaller/Scoop>`_.
|
||||
|
||||
.. code:: bash
|
||||
|
||||
choco install postgrest
|
||||
scoop install postgrest
|
||||
|
||||
.. include:: ../shared/installation.rst
|
||||
|
||||
.. _pg-dependency:
|
||||
|
||||
@@ -67,6 +21,12 @@ Supported PostgreSQL versions
|
||||
|
||||
PostgREST works with all PostgreSQL versions starting from 9.6.
|
||||
|
||||
.. note::
|
||||
|
||||
Support for PostgreSQL versions 9.6, 10 and 11 is deprecated. From this on version onwards, PostgREST will only support non-end-of-life PostgreSQL versions.
|
||||
|
||||
See https://www.postgresql.org/support/versioning/.
|
||||
|
||||
Running PostgREST
|
||||
=================
|
||||
|
||||
@@ -209,14 +169,15 @@ If you want to have a visual overview of your API in your browser you can add sw
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
swagger:
|
||||
image: swaggerapi/swagger-ui
|
||||
ports:
|
||||
- "8080:8080"
|
||||
expose:
|
||||
- "8080"
|
||||
environment:
|
||||
API_URL: http://localhost:3000/
|
||||
# in services:
|
||||
swagger:
|
||||
image: swaggerapi/swagger-ui
|
||||
ports:
|
||||
- "8080:8080"
|
||||
expose:
|
||||
- "8080"
|
||||
environment:
|
||||
API_URL: http://localhost:3000/
|
||||
|
||||
With this you can see the swagger-ui in your browser on port 8080.
|
||||
|
||||
@@ -227,10 +188,6 @@ Building from Source
|
||||
|
||||
When a pre-built binary does not exist for your system you can build the project from source.
|
||||
|
||||
.. note::
|
||||
|
||||
We discourage building and using PostgREST on **Alpine Linux** because of a reported GHC memory leak on that platform.
|
||||
|
||||
You can build PostgREST from source with `Stack <https://github.com/commercialhaskell/stack>`_. It will install any necessary Haskell dependencies on your system.
|
||||
|
||||
* `Install Stack <https://docs.haskellstack.org/en/stable/#how-to-install-stack>`_ for your platform
|
||||
@@ -242,7 +199,7 @@ You can build PostgREST from source with `Stack <https://github.com/commercialha
|
||||
Ubuntu/Debian libpq-dev, libgmp-dev, zlib1g-dev
|
||||
CentOS/Fedora/Red Hat postgresql-devel, zlib-devel, gmp-devel
|
||||
BSD postgresql12-client
|
||||
OS X libpq, gmp
|
||||
macOS libpq, gmp
|
||||
===================== =======================================
|
||||
|
||||
* Build and install binary
|
||||
|
||||
@@ -42,7 +42,7 @@ The first step is to create an Nginx configuration file that proxies requests to
|
||||
HTTPS
|
||||
-----
|
||||
|
||||
PostgREST aims to do one thing well: add an HTTP interface to a PostgreSQL database. To keep the code small and focused we do not implement HTTPS. Use a reverse proxy such as NGINX to add this, `here's how <https://nginx.org/en/docs/http/configuring_https_servers.html>`_. Note that some Platforms as a Service like Heroku also add SSL automatically in their load balancer.
|
||||
PostgREST aims to do one thing well: add an HTTP interface to a PostgreSQL database. To keep the code small and focused we do not implement HTTPS. Use a reverse proxy such as NGINX to add this, `here's how <https://nginx.org/en/docs/http/configuring_https_servers.html>`_.
|
||||
|
||||
Rate Limiting
|
||||
-------------
|
||||
@@ -55,7 +55,7 @@ Nginx supports "leaky bucket" rate limiting (see `official docs <https://nginx.o
|
||||
|
||||
This creates a shared memory zone called "login" to store a log of IP addresses that access the rate limited urls. The space reserved, 10 MB (:code:`10m`) will give us enough space to store a history of 160k requests. We have chosen to allow only allow one request per second (:code:`1r/s`).
|
||||
|
||||
Next we apply the zone to certain routes, like a hypothetical stored procedure called :code:`login`.
|
||||
Next we apply the zone to certain routes, like a hypothetical function called :code:`login`.
|
||||
|
||||
.. code-block:: nginx
|
||||
|
||||
@@ -73,17 +73,10 @@ Alternate URL Structure
|
||||
|
||||
As discussed in :ref:`singular_plural`, there are no special URL forms for singular resources in PostgREST, only operators for filtering. Thus there are no URLs like :code:`/people/1`. It would be specified instead as
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
GET /people?id=eq.1 HTTP/1.1
|
||||
Accept: application/vnd.pgrst.object+json
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/people?id=eq.1" \
|
||||
-H "Accept: application/vnd.pgrst.object+json"
|
||||
curl "http://localhost:3000/people?id=eq.1" \
|
||||
-H "Accept: application/vnd.pgrst.object+json"
|
||||
|
||||
This allows compound primary keys and makes the intent for singular response independent of a URL convention.
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
.. _schema_isolation:
|
||||
|
||||
Schema Isolation
|
||||
================
|
||||
|
||||
A PostgREST instance exposes all the tables, views, and functions of a single `PostgreSQL schema <https://www.postgresql.org/docs/current/ddl-schemas.html>`_ (a namespace of database objects). This means private data or implementation details can go inside different private schemas and be invisible to HTTP clients.
|
||||
|
||||
It is recommended that you don't expose tables on your API schema. Instead expose views and functions which insulate the internal details from the outside world.
|
||||
This allows you to change the internals of your schema and maintain backwards compatibility. It also keeps your code easier to refactor, and provides a natural way to do API versioning.
|
||||
|
||||
.. container:: svg-container-md
|
||||
|
||||
.. container:: img-dark
|
||||
|
||||
.. See https://github.com/sphinx-doc/sphinx/issues/2240#issuecomment-187366626
|
||||
|
||||
.. raw:: html
|
||||
|
||||
<object width="100%" data="../_static/sch-iso-dark.svg" type="image/svg+xml"></object>
|
||||
|
||||
.. container:: img-light
|
||||
|
||||
.. raw:: html
|
||||
|
||||
<object width="100%" data="../_static/sch-iso.svg" type="image/svg+xml"></object>
|
||||
@@ -1,33 +0,0 @@
|
||||
{ lib
|
||||
, buildPythonPackage
|
||||
, fetchFromGitHub
|
||||
, sphinx
|
||||
}:
|
||||
|
||||
buildPythonPackage rec {
|
||||
pname = "sphinx-copybutton";
|
||||
version = "0.4.0";
|
||||
|
||||
src = fetchFromGitHub {
|
||||
owner = "executablebooks";
|
||||
repo = "sphinx-copybutton";
|
||||
rev = "v${version}";
|
||||
sha256 = "sha256-vrEIvQeP7AMXSme1PBp0ox5k8Q1rz+1cbHIO+o17Jqc=";
|
||||
fetchSubmodules = true;
|
||||
};
|
||||
|
||||
propagatedBuildInputs = [
|
||||
sphinx
|
||||
];
|
||||
|
||||
doCheck = false; # no tests
|
||||
|
||||
pythonImportsCheck = [ "sphinx_copybutton" ];
|
||||
|
||||
meta = with lib; {
|
||||
description = "A small sphinx extension to add a \"copy\" button to code blocks";
|
||||
homepage = "https://github.com/executablebooks/sphinx-copybutton";
|
||||
license = licenses.mit;
|
||||
maintainers = with maintainers; [ Luflosi ];
|
||||
};
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
{ lib
|
||||
, buildPythonPackage
|
||||
, fetchPypi
|
||||
, sphinx
|
||||
}:
|
||||
|
||||
buildPythonPackage rec {
|
||||
pname = "sphinx-tabs";
|
||||
version = "3.2.0";
|
||||
|
||||
src = fetchPypi {
|
||||
inherit pname version;
|
||||
sha256 = "sha256:1970aahi6sa7c37cpz8nwgdb2xzf21rk6ykdd1m6w9wvxla7j4rk";
|
||||
};
|
||||
|
||||
propagatedBuildInputs = [
|
||||
sphinx
|
||||
];
|
||||
|
||||
doCheck = false;
|
||||
|
||||
pythonImportsCheck = [ "sphinx_tabs" ];
|
||||
|
||||
meta = with lib; {
|
||||
description = "Create tabbed content in Sphinx documentation when building HTML";
|
||||
homepage = "https://sphinx-tabs.readthedocs.io";
|
||||
license = licenses.mit;
|
||||
};
|
||||
}
|
||||
@@ -5,22 +5,20 @@ Create a SOAP endpoint
|
||||
|
||||
:author: `fjf2002 <https://github.com/fjf2002>`_
|
||||
|
||||
PostgREST now has XML support. With a bit of work, SOAP endpoints become possible.
|
||||
|
||||
Please note that PostgREST supports just ``text/xml`` MIME type in request/response headers ``Content-Type`` and ``Accept``.
|
||||
If you have to use other MIME types such as ``application/soap+xml``, you could manipulate the headers in your reverse proxy.
|
||||
|
||||
|
||||
PostgREST supports :ref:`custom_media`. With a bit of work, SOAP endpoints become possible.
|
||||
|
||||
Minimal Example
|
||||
---------------
|
||||
|
||||
This example will simply return the request body, inside a tag ``therequestbodywas``.
|
||||
|
||||
Add the following function to your PostgreSQL database:
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
CREATE OR REPLACE FUNCTION my_soap_endpoint(xml) RETURNS xml AS $$
|
||||
create domain "text/xml" as pg_catalog.xml;
|
||||
|
||||
CREATE OR REPLACE FUNCTION my_soap_endpoint(xml) RETURNS "text/xml" AS $$
|
||||
DECLARE
|
||||
nsarray CONSTANT text[][] := ARRAY[
|
||||
ARRAY['soapenv', 'http://schemas.xmlsoap.org/soap/envelope/']
|
||||
@@ -79,25 +77,6 @@ and should roughly look like:
|
||||
</soapenv:Body>
|
||||
</soapenv:Envelope>
|
||||
|
||||
Unfortunately the ``Accept: text/xml`` header is currently mandatory concerning PostgREST, otherwise it will respond
|
||||
with a ``Content-Type: application/json`` header and enclose the response with quotes.
|
||||
(You can check the returned headers by adding ``-v`` to the curl call.)
|
||||
|
||||
If your SOAP clients do not send the ``Accept: text/xml`` header, you can fix that in your nginx reverse proxy
|
||||
by adding something like ...
|
||||
|
||||
.. code-block:: nginx
|
||||
|
||||
set $accept $http_accept;
|
||||
if ($contentType ~ "^text/xml($|;)") {
|
||||
set $accept "text/xml";
|
||||
}
|
||||
proxy_set_header Accept $accept;
|
||||
|
||||
to your ``location`` nginx configuration.
|
||||
(The given example sets the ``Accept`` header for each request of Content-Type ``text/xml``.)
|
||||
|
||||
|
||||
A more elaborate example
|
||||
------------------------
|
||||
|
||||
@@ -121,7 +100,7 @@ potentially disclosing internals to the client, but instead handle the errors di
|
||||
xmlelement(NAME "soapenv:Body", body)
|
||||
);
|
||||
$function$;
|
||||
|
||||
|
||||
-- helper function
|
||||
CREATE OR REPLACE FUNCTION _soap_exception(
|
||||
faultcode text,
|
||||
@@ -137,9 +116,9 @@ potentially disclosing internals to the client, but instead handle the errors di
|
||||
)
|
||||
);
|
||||
$function$;
|
||||
|
||||
|
||||
CREATE OR REPLACE FUNCTION fraction_to_decimal(xml)
|
||||
RETURNS xml
|
||||
RETURNS "text/xml"
|
||||
LANGUAGE plpgsql
|
||||
AS $function$
|
||||
DECLARE
|
||||
@@ -207,14 +186,14 @@ The output should roughly look like:
|
||||
</soapenv:Body>
|
||||
</soapenv:Envelope>
|
||||
|
||||
|
||||
References
|
||||
----------
|
||||
|
||||
For more information concerning PostgREST, cf.
|
||||
|
||||
- :ref:`s_proc_single_unnamed`
|
||||
- :ref:`scalar_return_formats`
|
||||
- :ref:`Nginx reverse proxy <admin>`
|
||||
- :ref:`function_single_unnamed`
|
||||
- :ref:`custom_media`. See :ref:`any_handler`, if you need to support an ``application/soap+xml`` media type or if you want to respond with XML without sending a media type.
|
||||
- :ref:`Nginx reverse proxy <nginx>`
|
||||
|
||||
For SOAP reference, visit
|
||||
|
||||
|
||||
@@ -0,0 +1,326 @@
|
||||
|
||||
.. _providing_html_htmx:
|
||||
|
||||
Providing HTML Content Using Htmx
|
||||
=================================
|
||||
|
||||
:author: `Laurence Isla <https://github.com/laurenceisla>`_
|
||||
|
||||
This how-to shows a way to return HTML content and use the `htmx library <https://htmx.org/>`_ to handle the AJAX requests.
|
||||
Htmx expects an HTML response and uses it to replace an element inside the DOM (see the `htmx introduction <https://htmx.org/docs/#introduction>`_ in the docs).
|
||||
|
||||
.. image:: ../_static/how-tos/htmx-demo.gif
|
||||
|
||||
.. warning::
|
||||
|
||||
This is a proof of concept showing what can be achieved using both technologies.
|
||||
We are working on `plmustache <https://github.com/PostgREST/plmustache>`_ which will further improve the HTML aspect of this how-to.
|
||||
|
||||
Preparatory Configuration
|
||||
-------------------------
|
||||
|
||||
We will make a to-do app based on the :ref:`tut0`, so make sure to complete it before continuing.
|
||||
|
||||
To simplify things, we won't be using authentication, so grant all permissions on the ``todos`` table to the ``web_anon`` user.
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
grant all on api.todos to web_anon;
|
||||
grant usage, select on sequence api.todos_id_seq to web_anon;
|
||||
|
||||
Next, add the ``text/html`` as a :ref:`custom_media`. With this, PostgREST can identify the request made by your web browser (with the ``Accept: text/html`` header)
|
||||
and return a raw HTML document file.
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
create domain "text/html" as text;
|
||||
|
||||
Creating an HTML Response
|
||||
-------------------------
|
||||
|
||||
Let's create a function that returns a basic HTML file, using `Pico CSS <https://picocss.com>`_ for styling and
|
||||
`Ionicons <https://ionic.io/ionicons>`_ to show some icons later.
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
create or replace function api.index() returns "text/html" as $$
|
||||
select $html$
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>PostgREST + HTMX To-Do List</title>
|
||||
<!-- Pico CSS for CSS styling -->
|
||||
<link href="https://cdn.jsdelivr.net/npm/@picocss/pico@next/css/pico.min.css" rel="stylesheet" />
|
||||
</head>
|
||||
<body>
|
||||
<main class="container">
|
||||
<article>
|
||||
<h5 style="text-align: center;">
|
||||
PostgREST + HTMX To-Do List
|
||||
</h5>
|
||||
</article>
|
||||
</main>
|
||||
<!-- Script for Ionicons icons -->
|
||||
<script type="module" src="https://unpkg.com/ionicons@7.1.0/dist/ionicons/ionicons.esm.js"></script>
|
||||
<script nomodule src="https://unpkg.com/ionicons@7.1.0/dist/ionicons/ionicons.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
$html$;
|
||||
$$ language sql;
|
||||
|
||||
The web browser will open the web page at ``http://localhost:3000/rpc/index``.
|
||||
|
||||
.. image:: ../_static/how-tos/htmx-simple.jpg
|
||||
|
||||
.. _html_htmx_list_create:
|
||||
|
||||
Listing and Creating To-Dos
|
||||
---------------------------
|
||||
|
||||
Now, let's show a list of the to-dos already inserted in the database.
|
||||
For that, we'll also need a function to help us sanitize the HTML content that may be present in the task.
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
create or replace function api.sanitize_html(text) returns text as $$
|
||||
select replace(replace(replace(replace(replace($1, '&', '&'), '"', '"'),'>', '>'),'<', '<'), '''', ''')
|
||||
$$ language sql;
|
||||
|
||||
create or replace function api.html_todo(api.todos) returns text as $$
|
||||
select format($html$
|
||||
<div>
|
||||
<%2$s>
|
||||
%3$s
|
||||
</%2$s>
|
||||
</div>
|
||||
$html$,
|
||||
$1.id,
|
||||
case when $1.done then 's' else 'span' end,
|
||||
api.sanitize_html($1.task)
|
||||
);
|
||||
$$ language sql stable;
|
||||
|
||||
create or replace function api.html_all_todos() returns text as $$
|
||||
select coalesce(
|
||||
string_agg(api.html_todo(t), '<hr/>' order by t.id),
|
||||
'<p><em>There is nothing else to do.</em></p>'
|
||||
)
|
||||
from api.todos t;
|
||||
$$ language sql;
|
||||
|
||||
These two functions are used to build the to-do list template. We won't use them as PostgREST endpoints.
|
||||
|
||||
- The ``api.html_todo`` function uses the table ``api.todos`` as a parameter and formats each item into a list element ``<li>``.
|
||||
The PostgreSQL `format <https://www.postgresql.org/docs/current/functions-string.html#FUNCTIONS-STRING-FORMAT>`_ is useful to that end.
|
||||
It replaces the values according to the position in the template, e.g. ``%1$s`` will be replaced with the value of ``$1.id`` (the first parameter).
|
||||
|
||||
- The ``api.html_all_todos`` function returns the ``<ul>`` wrapper for all the list elements.
|
||||
It uses `string_arg <https://www.postgresql.org/docs/current/functions-aggregate.html>`_ to concatenate all the to-dos in a single text value.
|
||||
It also returns an alternative message, instead of a list, when the ``api.todos`` table is empty.
|
||||
|
||||
Next, let's add an endpoint to register a to-do in the database and modify the ``/rpc/index`` page accordingly.
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
create or replace function api.add_todo(_task text) returns "text/html" as $$
|
||||
insert into api.todos(task) values (_task);
|
||||
select api.html_all_todos();
|
||||
$$ language sql;
|
||||
|
||||
create or replace function api.index() returns "text/html" as $$
|
||||
select $html$
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>PostgREST + HTMX To-Do List</title>
|
||||
<!-- Pico CSS for CSS styling -->
|
||||
<link href="https://cdn.jsdelivr.net/npm/@picocss/pico@next/css/pico.min.css" rel="stylesheet"/>
|
||||
<!-- htmx for AJAX requests -->
|
||||
<script src="https://unpkg.com/htmx.org"></script>
|
||||
</head>
|
||||
<body>
|
||||
<main class="container"
|
||||
style="max-width: 600px"
|
||||
hx-headers='{"Accept": "text/html"}'>
|
||||
<article>
|
||||
<h5 style="text-align: center;">
|
||||
PostgREST + HTMX To-Do List
|
||||
</h5>
|
||||
<form hx-post="/rpc/add_todo"
|
||||
hx-target="#todo-list-area"
|
||||
hx-trigger="submit"
|
||||
hx-on="htmx:afterRequest: this.reset()">
|
||||
<input type="text" name="_task" placeholder="Add a todo...">
|
||||
</form>
|
||||
<div id="todo-list-area">
|
||||
$html$
|
||||
|| api.html_all_todos() ||
|
||||
$html$
|
||||
<div>
|
||||
</article>
|
||||
</main>
|
||||
<!-- Script for Ionicons icons -->
|
||||
<script type="module" src="https://unpkg.com/ionicons@7.1.0/dist/ionicons/ionicons.esm.js"></script>
|
||||
<script nomodule src="https://unpkg.com/ionicons@7.1.0/dist/ionicons/ionicons.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
$html$;
|
||||
$$ language sql;
|
||||
|
||||
- The ``/rpc/add_todo`` endpoint allows us to add a new to-do using the ``_task`` parameter and returns an ``html`` with all the to-dos in the database.
|
||||
|
||||
- The ``/rpc/index`` now adds the ``hx-headers='{"Accept": "text/html"}'`` tag to the ``<body>``.
|
||||
This will make sure that all htmx elements inside the body send this header, otherwise PostgREST won't recognize it as HTML.
|
||||
|
||||
There is also a ``<form>`` element that uses the htmx library. Let's break it down:
|
||||
|
||||
+ ``hx-post="/rpc/add_todo"``: sends an AJAX POST request to the ``/rpc/add_todo`` endpoint, with the value of the ``_task`` from the ``<input>`` element.
|
||||
|
||||
+ ``hx-target="#todo-list-area"``: the HTML content returned from the request will go inside ``<div id="todo-list-area"></div>`` (which is the list of to-dos).
|
||||
|
||||
+ ``hx-trigger="submit"``: htmx will do this request when submitting the form (by pressing enter while inside the ``<input>``).
|
||||
|
||||
+ ``hx-on="htmx:afterRequest: this.reset()">``: this is a Javascript command that clears the form `after the request is done <https://htmx.org/events/#htmx:afterRequest>`_.
|
||||
|
||||
With this, the ``http://localhost:3000/rpc/index`` page lists all the todos and adds new ones by submitting tasks in the input element.
|
||||
Don't forget to refresh the :ref:`schema cache <schema_reloading>`.
|
||||
|
||||
.. image:: ../_static/how-tos/htmx-insert.gif
|
||||
|
||||
Editing and Deleting To-Dos
|
||||
---------------------------
|
||||
|
||||
Now, let's modify ``api.html_todo`` and make it more functional.
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
create or replace function api.html_todo(api.todos) returns text as $$
|
||||
select format($html$
|
||||
<div class="grid">
|
||||
<div id="todo-edit-area-%1$s">
|
||||
<form id="edit-task-state-%1$s"
|
||||
hx-post="/rpc/change_todo_state"
|
||||
hx-vals='{"_id": %1$s, "_done": %4$s}'
|
||||
hx-target="#todo-list-area"
|
||||
hx-trigger="click">
|
||||
<%2$s style="cursor: pointer">
|
||||
%3$s
|
||||
</%2$s>
|
||||
</form>
|
||||
</div>
|
||||
<div style="text-align: right">
|
||||
<button class="outline"
|
||||
hx-get="/rpc/html_editable_task"
|
||||
hx-vals='{"_id": "%1$s"}'
|
||||
hx-target="#todo-edit-area-%1$s"
|
||||
hx-trigger="click">
|
||||
<span>
|
||||
<ion-icon name="create"></ion-icon>
|
||||
</span>
|
||||
</button>
|
||||
<button class="outline contrast"
|
||||
hx-post="/rpc/delete_todo"
|
||||
hx-vals='{"_id": %1$s}'
|
||||
hx-target="#todo-list-area"
|
||||
hx-trigger="click">
|
||||
<span>
|
||||
<ion-icon name="trash" style="color: #f87171"></ion-icon>
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
$html$,
|
||||
$1.id,
|
||||
case when $1.done then 's' else 'span' end,
|
||||
api.sanitize_html($1.task),
|
||||
(not $1.done)::text
|
||||
);
|
||||
$$ language sql stable;
|
||||
|
||||
Let's deconstruct the new htmx features added:
|
||||
|
||||
- The ``<form>`` element is configured as follows:
|
||||
|
||||
+ ``hx-post="/rpc/change_todo_state"``: does an AJAX POST request to that endpoint. It will toggle the ``done`` state of the to-do.
|
||||
|
||||
+ ``hx-vals='{"_id": %1$s, "_done": %4$s}'``: adds the parameters to the request.
|
||||
This is an alternative to using hidden inputs inside the ``<form>``.
|
||||
|
||||
+ ``hx-trigger="click"``: htmx does the request after clicking on the element.
|
||||
|
||||
- For the first ``<button>``:
|
||||
|
||||
+ ``hx-get="/rpc/html_editable_task"``: it does an AJAX GET request to that endpoint.
|
||||
It returns an HTML with an input that will allow us to edit the task.
|
||||
|
||||
+ ``hx-target="#todo-edit-area"``: the returned HTML will replace the element with this id.
|
||||
In this case, this replaces an individual task, not the whole list.
|
||||
|
||||
+ ``hx-vals='{"id": "eq.%1$s"}'``: adds the query parameters to the GET request.
|
||||
Note that this needs the ``eq.`` operator because it represents a table column not a function parameter.
|
||||
|
||||
- For the second ``<button>``:
|
||||
|
||||
+ ``hx-post="/rpc/delete_todo"``: this post request will delete the corresponding to-do.
|
||||
|
||||
Clicking on the first button will enable the task editing.
|
||||
That's why we create the ``api.html_editable_task`` function as an endpoint:
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
create or replace function api.html_editable_task(_id int) returns "text/html" as $$
|
||||
select format ($html$
|
||||
<form id="edit-task-%1$s"
|
||||
hx-post="/rpc/change_todo_task"
|
||||
hx-headers='{"Accept": "text/html"}'
|
||||
hx-vals='{"_id": %1$s}'
|
||||
hx-target="#todo-list-area"
|
||||
hx-trigger="submit,focusout">
|
||||
<input id="task-%1$s" type="text" name="_task" value="%2$s" autofocus>
|
||||
</form>
|
||||
$html$,
|
||||
id,
|
||||
api.sanitize_html(task)
|
||||
)
|
||||
from api.todos
|
||||
where id = _id;
|
||||
$$ language sql;
|
||||
|
||||
In this example, this will return an input field that allows us to edit the corresponding to-do task.
|
||||
|
||||
Finally, let's add the endpoints that will modify and delete the to-dos in the database.
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
create or replace function api.change_todo_state(_id int, _done boolean) returns "text/html" as $$
|
||||
update api.todos set done = _done where id = _id;
|
||||
select api.html_all_todos();
|
||||
$$ language sql;
|
||||
|
||||
create or replace function api.change_todo_task(_id int, _task text) returns "text/html" as $$
|
||||
update api.todos set task = _task where id = _id;
|
||||
select api.html_all_todos();
|
||||
$$ language sql;
|
||||
|
||||
create or replace function api.delete_todo(_id int) returns "text/html" as $$
|
||||
delete from api.todos where id = _id;
|
||||
select api.html_all_todos();
|
||||
$$ language sql;
|
||||
|
||||
All of those functions return an HTML list of to-dos that will replace the outdated one:
|
||||
|
||||
- The ``api.change_todo_state`` function updates the ``done`` column using the ``_id`` and the ``_done`` values from the request.
|
||||
|
||||
- The ``api.delete_todo`` function deletes a to-do using the ``_id`` value from the request.
|
||||
|
||||
- The ``api.change_todo_task`` function modifies the ``task`` column using the ``_id`` and the ``_task`` value from the request.
|
||||
|
||||
After refreshing the :ref:`schema cache <schema_reloading>`, the page at ``http://localhost:3000/rpc/index`` will allow us to edit, delete and complete any to-do.
|
||||
|
||||
.. image:: ../_static/how-tos/htmx-edit-delete.gif
|
||||
|
||||
With that, we completed the to-do list functionality.
|
||||
@@ -26,18 +26,42 @@ First, we need a public table for storing the files.
|
||||
, blob bytea
|
||||
);
|
||||
|
||||
Let's assume this table contains an image of two cute kittens with id 42.
|
||||
We can retrieve this image in binary format from our PostgREST API by requesting :code:`/files?select=blob&id=eq.42` with the :code:`Accept: application/octet-stream` header.
|
||||
Unfortunately, putting the URL into the :code:`src` of an :code:`<img>` tag will not work.
|
||||
That's because browsers do not send the required :code:`Accept: application/octet-stream` header.
|
||||
Let's assume this table contains an image of two cute kittens with id 42. We can retrieve this image in binary format from our PostgREST API by using :ref:`custom_media`:
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
create domain "application/octet-stream" as bytea;
|
||||
|
||||
create or replace function file(id int) returns "application/octet-stream" as $$
|
||||
select blob from files where id = file.id;
|
||||
$$ language sql;
|
||||
|
||||
Now we can request the RPC endpoint :code:`/rpc/file?id=42` with the :code:`Accept: application/octet-stream` header.
|
||||
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl "localhost:3000/rpc/file?id=42" -H "Accept: application/octet-stream"
|
||||
|
||||
|
||||
Unfortunately, putting the URL into the :code:`src` of an :code:`<img>` tag will not work. That's because browsers do not send the required :code:`Accept: application/octet-stream` header.
|
||||
Instead, the :code:`Accept: image/webp` header is sent by many web browsers by default.
|
||||
|
||||
Luckily we can change the accepted media type in the function like so:
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
create domain "image/webp" as bytea;
|
||||
|
||||
create or replace function file(id int) returns "image/webp" as $$
|
||||
select blob from files where id = file.id;
|
||||
$$ language sql;
|
||||
|
||||
Luckily we can specify the accepted media types in the :ref:`raw-media-types` configuration variable.
|
||||
In this case, the :code:`Accept: image/webp` header is sent by many web browsers by default, so let's add it to the configuration variable, like this: :code:`raw-media-types="image/webp"`.
|
||||
Now, the image will be displayed in the HTML page:
|
||||
|
||||
.. code-block:: html
|
||||
|
||||
<img src="http://localhost:3000/files?select=blob&id=eq.42" alt="Cute Kittens"/>
|
||||
<img src="http://localhost:3000/file?id=42" alt="Cute Kittens"/>
|
||||
|
||||
Improved Version
|
||||
----------------
|
||||
@@ -57,16 +81,20 @@ First, in addition to the minimal example, we need to store the media types and
|
||||
.. code-block:: postgres
|
||||
|
||||
alter table files
|
||||
add column type text,
|
||||
add column type text generated always as (byteamagic_mime(substr(blob, 0, 4100))) stored,
|
||||
add column name text;
|
||||
|
||||
Next, we set up an RPC endpoint that sets the content type and filename.
|
||||
This uses the :code:`byteamagic_mime()` function from the `pg_byteamagic extension <https://github.com/nmandery/pg_byteamagic>`_ to automatically generate the type in the :code:`files` table. To guess the type of a file, it's generally enough to look at the beginning of the file, which is more efficient.
|
||||
|
||||
Next, we set modify the function to set the content type and filename.
|
||||
We use this opportunity to configure some basic, client-side caching.
|
||||
For production, you probably want to configure additional caches, e.g. on the :ref:`reverse proxy <admin>`.
|
||||
For production, you probably want to configure additional caches, e.g. on the :ref:`reverse proxy <nginx>`.
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
create function file(id int) returns bytea as
|
||||
create domain "*/*" as bytea;
|
||||
|
||||
create function file(id int) returns "*/*" as
|
||||
$$
|
||||
declare headers text;
|
||||
declare blob bytea;
|
||||
@@ -79,7 +107,7 @@ For production, you probably want to configure additional caches, e.g. on the :r
|
||||
from files where files.id = file.id into headers;
|
||||
perform set_config('response.headers', headers, true);
|
||||
select files.blob from files where files.id = file.id into blob;
|
||||
if found
|
||||
if FOUND -- special var, see https://www.postgresql.org/docs/current/plpgsql-statements.html#PLPGSQL-STATEMENTS-DIAGNOSTICS
|
||||
then return(blob);
|
||||
else raise sqlstate 'PT404' using
|
||||
message = 'NOT FOUND',
|
||||
|
||||
@@ -31,7 +31,7 @@ As in :ref:`sql_user_management`, we create a :code:`basic_auth` schema:
|
||||
-- We put things inside the basic_auth schema to hide
|
||||
-- them from public view. Certain public procs/views will
|
||||
-- refer to helpers and tables inside.
|
||||
CREATE SCHEMA IF NOT EXISTS basic_auth;
|
||||
CREATE SCHEMA basic_auth;
|
||||
|
||||
|
||||
As in :ref:`sql_user_management`, we create the :code:`pgcrypto` and :code:`pgjwt` extensions. Here we prefer to put the extensions in its own schemas:
|
||||
@@ -40,7 +40,7 @@ As in :ref:`sql_user_management`, we create the :code:`pgcrypto` and :code:`pgjw
|
||||
|
||||
CREATE SCHEMA ext_pgcrypto;
|
||||
ALTER SCHEMA ext_pgcrypto OWNER TO postgres;
|
||||
CREATE EXTENSION IF NOT EXISTS pgcrypto WITH SCHEMA ext_pgcrypto;
|
||||
CREATE EXTENSION pgcrypto WITH SCHEMA ext_pgcrypto;
|
||||
|
||||
|
||||
Concerning the `pgjwt extension <https://github.com/michelp/pgjwt>`_, please cf. to :ref:`client_auth`.
|
||||
@@ -49,12 +49,12 @@ Concerning the `pgjwt extension <https://github.com/michelp/pgjwt>`_, please cf.
|
||||
|
||||
CREATE SCHEMA ext_pgjwt;
|
||||
ALTER SCHEMA ext_pgjwt OWNER TO postgres;
|
||||
CREATE EXTENSION IF NOT EXISTS pgjwt WITH SCHEMA ext_pgjwt;
|
||||
CREATE EXTENSION pgjwt WITH SCHEMA ext_pgjwt;
|
||||
|
||||
|
||||
In order to be able to work with postgres' SCRAM-SHA-256 password hashes, we also need the PBKDF2 key derivation function. Luckily there is `a PL/pgSQL implementation on stackoverflow <https://stackoverflow.com/q/47162200/2337147>`_:
|
||||
In order to be able to work with postgres' SCRAM-SHA-256 password hashes, we also need the PBKDF2 key derivation function. Luckily there is `a PL/pgSQL implementation on stackoverflow <https://stackoverflow.com/a/72805848>`_:
|
||||
|
||||
.. code-block:: plpgsql
|
||||
.. code-block:: postgres
|
||||
|
||||
CREATE FUNCTION basic_auth.pbkdf2(salt bytea, pw text, count integer, desired_length integer, algorithm text) RETURNS bytea
|
||||
LANGUAGE plpgsql IMMUTABLE
|
||||
@@ -117,10 +117,10 @@ In order to be able to work with postgres' SCRAM-SHA-256 password hashes, we als
|
||||
ALTER FUNCTION basic_auth.pbkdf2(salt bytea, pw text, count integer, desired_length integer, algorithm text) OWNER TO postgres;
|
||||
|
||||
|
||||
Analogous to :ref:`sql_user_management` creates the function :code:`basic_auth.user_role`, we create a helper function to check the user's password, here with another name and signature (since we want the username, not an email address).
|
||||
Analogous to how :ref:`sql_user_management` creates the function :code:`basic_auth.user_role`, we create a helper function to check the user's password, here with another name and signature (since we want the username, not an email address).
|
||||
But contrary to :ref:`sql_user_management`, this function does not use a dedicated :code:`users` table with passwords, but instead utilizes the built-in table `pg_catalog.pg_authid <https://www.postgresql.org/docs/current/catalog-pg-authid.html>`_:
|
||||
|
||||
.. code-block:: plpgsql
|
||||
.. code-block:: postgres
|
||||
|
||||
CREATE FUNCTION basic_auth.check_user_pass(username text, password text) RETURNS name
|
||||
LANGUAGE sql
|
||||
@@ -160,22 +160,17 @@ Logins
|
||||
As described in :ref:`client_auth`, we'll create a JWT token inside our login function. Note that you'll need to adjust the secret key which is hard-coded in this example to a secure (at least thirty-two character) secret of your choosing.
|
||||
|
||||
|
||||
.. code-block:: plpgsql
|
||||
|
||||
CREATE TYPE basic_auth.jwt_token AS (
|
||||
token text
|
||||
);
|
||||
.. code-block:: postgres
|
||||
|
||||
-- if you are not using psql, you need to replace :DBNAME with the current database's name.
|
||||
ALTER DATABASE :DBNAME SET "app.jwt_secret" to 'reallyreallyreallyreallyverysafe';
|
||||
|
||||
|
||||
CREATE FUNCTION public.login(username text, password text) RETURNS basic_auth.jwt_token
|
||||
CREATE FUNCTION public.login(username text, password text, OUT token text)
|
||||
LANGUAGE plpgsql security definer
|
||||
AS $$
|
||||
DECLARE
|
||||
_role name;
|
||||
result basic_auth.jwt_token;
|
||||
BEGIN
|
||||
-- check email and password
|
||||
SELECT basic_auth.check_user_pass(username, password) INTO _role;
|
||||
@@ -190,8 +185,7 @@ As described in :ref:`client_auth`, we'll create a JWT token inside our login fu
|
||||
SELECT login.username as role,
|
||||
extract(epoch FROM now())::integer + 60*60 AS exp
|
||||
) r
|
||||
INTO result;
|
||||
RETURN result;
|
||||
INTO token;
|
||||
END;
|
||||
$$;
|
||||
|
||||
@@ -259,19 +253,11 @@ Test at the REST level
|
||||
~~~~~~~~~~~~~~~~~~~~~~
|
||||
An API request to call this function would look like:
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
POST /rpc/login HTTP/1.1
|
||||
|
||||
{ "username": "foo", "password": "bar" }
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/rpc/login" \
|
||||
-X POST -H "Content-Type: application/json" \
|
||||
-d '{ "username": "foo", "password": "bar" }'
|
||||
curl "http://localhost:3000/rpc/login" \
|
||||
-X POST -H "Content-Type: application/json" \
|
||||
-d '{ "username": "foo", "password": "bar" }'
|
||||
|
||||
The response would look like the snippet below. Try decoding the token at `jwt.io <https://jwt.io/>`_. (It was encoded with a secret of :code:`reallyreallyreallyreallyverysafe` as specified in the SQL code above. You'll want to change this secret in your app!)
|
||||
|
||||
@@ -296,31 +282,18 @@ Let's add a table, intended for the :code:`foo` user:
|
||||
|
||||
Now try to get the table's contents with:
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
GET /foobar HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/foobar"
|
||||
curl "http://localhost:3000/foobar"
|
||||
|
||||
|
||||
This should fail --- of course, we haven't specified the user, thus PostgREST falls back to the :code:`anon` user and denies access.
|
||||
Add an :code:`Authorization` header. Please use the token value from the login function call above instead of the one provided below.
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
GET /foobar HTTP/1.1
|
||||
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiZm9vIiwiZXhwIjoxNjY4MTkyMjAyfQ.zzdHCBjfkqDQLQ8D7CHO3cIALF6KBCsfPTWgwhCiHCY
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/foobar" \
|
||||
-H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiZm9vIiwiZXhwIjoxNjY4MTkyMjAyfQ.zzdHCBjfkqDQLQ8D7CHO3cIALF6KBCsfPTWgwhCiHCY"
|
||||
curl "http://localhost:3000/foobar" \
|
||||
-H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiZm9vIiwiZXhwIjoxNjY4MTkyMjAyfQ.zzdHCBjfkqDQLQ8D7CHO3cIALF6KBCsfPTWgwhCiHCY"
|
||||
|
||||
|
||||
This will fail again --- we get :code:`Permission denied to set role`. We forgot to allow the authenticator role to switch into this user by executing:
|
||||
|
||||
@@ -17,9 +17,8 @@ First we'll need a table to keep track of our users:
|
||||
-- We put things inside the basic_auth schema to hide
|
||||
-- them from public view. Certain public procs/views will
|
||||
-- refer to helpers and tables inside.
|
||||
create schema if not exists basic_auth;
|
||||
|
||||
create table if not exists
|
||||
create table
|
||||
basic_auth.users (
|
||||
email text primary key check ( email ~* '^.+@.+\..+$' ),
|
||||
pass text not null check (length(pass) < 512),
|
||||
@@ -28,9 +27,9 @@ First we'll need a table to keep track of our users:
|
||||
|
||||
We would like the role to be a foreign key to actual database roles, however PostgreSQL does not support these constraints against the :code:`pg_roles` table. We'll use a trigger to manually enforce it.
|
||||
|
||||
.. code-block:: plpgsql
|
||||
.. code-block:: postgres
|
||||
|
||||
create or replace function
|
||||
create function
|
||||
basic_auth.check_role_exists() returns trigger as $$
|
||||
begin
|
||||
if not exists (select 1 from pg_roles as r where r.rolname = new.role) then
|
||||
@@ -42,7 +41,6 @@ We would like the role to be a foreign key to actual database roles, however Pos
|
||||
end
|
||||
$$ language plpgsql;
|
||||
|
||||
drop trigger if exists ensure_user_role_exists on basic_auth.users;
|
||||
create constraint trigger ensure_user_role_exists
|
||||
after insert or update on basic_auth.users
|
||||
for each row
|
||||
@@ -50,11 +48,11 @@ We would like the role to be a foreign key to actual database roles, however Pos
|
||||
|
||||
Next we'll use the pgcrypto extension and a trigger to keep passwords safe in the :code:`users` table.
|
||||
|
||||
.. code-block:: plpgsql
|
||||
.. code-block:: postgres
|
||||
|
||||
create extension if not exists pgcrypto;
|
||||
create extension pgcrypto;
|
||||
|
||||
create or replace function
|
||||
create function
|
||||
basic_auth.encrypt_pass() returns trigger as $$
|
||||
begin
|
||||
if tg_op = 'INSERT' or new.pass <> old.pass then
|
||||
@@ -64,7 +62,6 @@ Next we'll use the pgcrypto extension and a trigger to keep passwords safe in th
|
||||
end
|
||||
$$ language plpgsql;
|
||||
|
||||
drop trigger if exists encrypt_pass on basic_auth.users;
|
||||
create trigger encrypt_pass
|
||||
before insert or update on basic_auth.users
|
||||
for each row
|
||||
@@ -72,9 +69,9 @@ Next we'll use the pgcrypto extension and a trigger to keep passwords safe in th
|
||||
|
||||
With the table in place we can make a helper to check a password against the encrypted column. It returns the database role for a user if the email and password are correct.
|
||||
|
||||
.. code-block:: plpgsql
|
||||
.. code-block:: postgres
|
||||
|
||||
create or replace function
|
||||
create function
|
||||
basic_auth.user_role(email text, pass text) returns name
|
||||
language plpgsql
|
||||
as $$
|
||||
@@ -118,15 +115,11 @@ JWT from SQL
|
||||
|
||||
You can create JWT tokens in SQL using the `pgjwt extension <https://github.com/michelp/pgjwt>`_. It's simple and requires only pgcrypto. If you're on an environment like Amazon RDS which doesn't support installing new extensions, you can still manually run the `SQL inside pgjwt <https://github.com/michelp/pgjwt/blob/master/pgjwt--0.1.1.sql>`_ (you'll need to replace ``@extschema@`` with another schema or just delete it) which creates the functions you will need.
|
||||
|
||||
Next write a stored procedure that returns the token. The one below returns a token with a hard-coded role, which expires five minutes after it was issued. Note this function has a hard-coded secret as well.
|
||||
Next write a function that returns the token. The one below returns a token with a hard-coded role, which expires five minutes after it was issued. Note this function has a hard-coded secret as well.
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
CREATE TYPE jwt_token AS (
|
||||
token text
|
||||
);
|
||||
|
||||
CREATE FUNCTION jwt_test() RETURNS public.jwt_token AS $$
|
||||
CREATE FUNCTION jwt_test(OUT token text) AS $$
|
||||
SELECT public.sign(
|
||||
row_to_json(r), 'reallyreallyreallyreallyverysafe'
|
||||
) AS token
|
||||
@@ -141,7 +134,7 @@ PostgREST exposes this function to clients via a POST request to ``/rpc/jwt_test
|
||||
|
||||
.. note::
|
||||
|
||||
To avoid hard-coding the secret in stored procedures, save it as a property of the database.
|
||||
To avoid hard-coding the secret in functions, save it as a property of the database.
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
@@ -161,17 +154,11 @@ As described in `JWT from SQL`_, we'll create a JWT inside our login function. N
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
-- add type
|
||||
CREATE TYPE basic_auth.jwt_token AS (
|
||||
token text
|
||||
);
|
||||
|
||||
-- login should be on your exposed schema
|
||||
create or replace function
|
||||
login(email text, pass text) returns basic_auth.jwt_token as $$
|
||||
create function
|
||||
login(email text, pass text, out token text) as $$
|
||||
declare
|
||||
_role name;
|
||||
result basic_auth.jwt_token;
|
||||
begin
|
||||
-- check email and password
|
||||
select basic_auth.user_role(email, pass) into _role;
|
||||
@@ -186,8 +173,7 @@ As described in `JWT from SQL`_, we'll create a JWT inside our login function. N
|
||||
select _role as role, login.email as email,
|
||||
extract(epoch from now())::integer + 60*60 as exp
|
||||
) r
|
||||
into result;
|
||||
return result;
|
||||
into token;
|
||||
end;
|
||||
$$ language plpgsql security definer;
|
||||
|
||||
@@ -199,19 +185,11 @@ the anonymous user :code:`anon` doesn't need permission to read the :code:`basic
|
||||
|
||||
An API request to call this function would look like:
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
POST /rpc/login HTTP/1.1
|
||||
|
||||
{ "email": "foo@bar.com", "pass": "foobar" }
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/rpc/login" \
|
||||
-X POST -H "Content-Type: application/json" \
|
||||
-d '{ "email": "foo@bar.com", "pass": "foobar" }'
|
||||
curl "http://localhost:3000/rpc/login" \
|
||||
-X POST -H "Content-Type: application/json" \
|
||||
-d '{ "email": "foo@bar.com", "pass": "foobar" }'
|
||||
|
||||
The response would look like the snippet below. Try decoding the token at `jwt.io <https://jwt.io/>`_. (It was encoded with a secret of :code:`reallyreallyreallyreallyverysafe` as specified in the SQL code above. You'll want to change this secret in your app!)
|
||||
|
||||
|
||||
@@ -5,133 +5,13 @@ Working with PostgreSQL data types
|
||||
|
||||
:author: `Laurence Isla <https://github.com/laurenceisla>`_
|
||||
|
||||
PostgREST makes use of PostgreSQL string representations to work with data types. Thanks to this, you can use special values, such as ``now`` for timestamps, ``yes`` for booleans or time values including the time zones. This page describes how you can take advantage of these string representations to perform operations on different PostgreSQL data types.
|
||||
PostgREST makes use of PostgreSQL string representations to work with data types. Thanks to this, you can use special values, such as ``now`` for timestamps, ``yes`` for booleans or time values including the time zones. This page describes how you can take advantage of these string representations and some alternatives to perform operations on different PostgreSQL data types.
|
||||
|
||||
.. contents::
|
||||
:local:
|
||||
:depth: 1
|
||||
|
||||
Timestamps
|
||||
----------
|
||||
|
||||
You can use the **time zone** to filter or send data if needed.
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
create table reports (
|
||||
id int primary key
|
||||
, due_date timestamptz
|
||||
);
|
||||
|
||||
Suppose you are located in Sydney and want create a report with the date in the local time zone. Your request should look like this:
|
||||
|
||||
.. tabs::
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
POST /reports HTTP/1.1
|
||||
Content-Type: application/json
|
||||
|
||||
[{ "id": 1, "due_date": "2022-02-24 11:10:15 Australia/Sydney" },
|
||||
{ "id": 2, "due_date": "2022-02-27 22:00:00 Australia/Sydney" }]
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/reports" \
|
||||
-X POST -H "Content-Type: application/json" \
|
||||
-d '[{ "id": 1, "due_date": "2022-02-24 11:10:15 Australia/Sydney" },{ "id": 2, "due_date": "2022-02-27 22:00:00 Australia/Sydney" }]'
|
||||
|
||||
Someone located in Cairo can retrieve the data using their local time, too:
|
||||
|
||||
.. tabs::
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
GET /reports?due_date=eq.2022-02-24+02:10:15+Africa/Cairo HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/reports?due_date=eq.2022-02-24+02:10:15+Africa/Cairo"
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
[
|
||||
{
|
||||
"id": 1,
|
||||
"due_date": "2022-02-23T19:10:15-05:00"
|
||||
}
|
||||
]
|
||||
|
||||
The response has the date in the time zone configured by the server: ``UTC -05:00``.
|
||||
|
||||
You can use other comparative filters and also all the `PostgreSQL special date/time input values <https://www.postgresql.org/docs/current/datatype-datetime.html#DATATYPE-DATETIME-SPECIAL-TABLE>`_ as illustrated in this example:
|
||||
|
||||
.. tabs::
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
GET /reports?or=(and(due_date.gte.today,due_date.lte.tomorrow),and(due_date.gt.-infinity,due_date.lte.epoch)) HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/reports?or=(and(due_date.gte.today,due_date.lte.tomorrow),and(due_date.gt.-infinity,due_date.lte.epoch))"
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
[
|
||||
{
|
||||
"id": 2,
|
||||
"due_date": "2022-02-27T06:00:00-05:00"
|
||||
}
|
||||
]
|
||||
|
||||
JSON
|
||||
----
|
||||
|
||||
To work with a ``json`` type column, you can handle the value as a JSON object.
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
create table products (
|
||||
id int primary key,
|
||||
name text unique,
|
||||
extra_info json
|
||||
);
|
||||
|
||||
You can insert a new product using a JSON object for the ``extra_info`` column:
|
||||
|
||||
.. tabs::
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
POST /products HTTP/1.1
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"id": 1,
|
||||
"name": "Canned fish",
|
||||
"extra_info": {
|
||||
"expiry_date": "2025-12-31",
|
||||
"exportable": true
|
||||
}
|
||||
}
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/products" \
|
||||
-X POST -H "Content-Type: application/json" \
|
||||
-d @- << EOF
|
||||
{
|
||||
"id": 1,
|
||||
"name": "Canned fish",
|
||||
"extra_info": {
|
||||
"expiry_date": "2025-12-31",
|
||||
"exportable": true
|
||||
}
|
||||
}
|
||||
EOF
|
||||
|
||||
To query and filter the data see :ref:`json_columns` for a complete reference.
|
||||
.. NOTE: Titles are ordered alphabetically. New entries should respect this order.
|
||||
|
||||
Arrays
|
||||
------
|
||||
@@ -149,61 +29,33 @@ To handle `array types <https://www.postgresql.org/docs/current/arrays.html>`_ y
|
||||
|
||||
You can insert a new value using string representation.
|
||||
|
||||
.. tabs::
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
POST /movies HTTP/1.1
|
||||
Content-Type: application/json
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3000/movies" \
|
||||
-X POST -H "Content-Type: application/json" \
|
||||
-d @- << EOF
|
||||
{
|
||||
"id": 1,
|
||||
"title": "Paddington",
|
||||
"tags": "{family,comedy,not streamable}",
|
||||
"performance_times": "{12:40,15:00,20:00}"
|
||||
}
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/movies" \
|
||||
-X POST -H "Content-Type: application/json" \
|
||||
-d @- << EOF
|
||||
{
|
||||
"id": 1,
|
||||
"title": "Paddington",
|
||||
"tags": "{family,comedy,not streamable}",
|
||||
"performance_times": "{12:40,15:00,20:00}"
|
||||
}
|
||||
EOF
|
||||
EOF
|
||||
|
||||
Or you could send the same data using JSON array format:
|
||||
|
||||
.. tabs::
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
POST /movies HTTP/1.1
|
||||
Content-Type: application/json
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3000/movies" \
|
||||
-X POST -H "Content-Type: application/json" \
|
||||
-d @- << EOF
|
||||
{
|
||||
"id": 1,
|
||||
"title": "Paddington",
|
||||
"tags": ["family", "comedy", "not streamable"],
|
||||
"performance_times": ["12:40", "15:00", "20:00"]
|
||||
}
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/movies" \
|
||||
-X POST -H "Content-Type: application/json" \
|
||||
-d @- << EOF
|
||||
{
|
||||
"id": 1,
|
||||
"title": "Paddington",
|
||||
"tags": ["family", "comedy", "not streamable"],
|
||||
"performance_times": ["12:40", "15:00", "20:00"]
|
||||
}
|
||||
EOF
|
||||
EOF
|
||||
|
||||
To query the data you can use arrow operators. See :ref:`composite_array_columns`.
|
||||
|
||||
@@ -220,38 +72,21 @@ Similarly to one-dimensional arrays, both the string representation and JSON arr
|
||||
|
||||
You can now update the item using JSON array format:
|
||||
|
||||
.. tabs::
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
PATCH /movies?id=eq.1 HTTP/1.1
|
||||
Content-Type: application/json
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3000/movies?id=eq.1" \
|
||||
-X PATCH -H "Content-Type: application/json" \
|
||||
-d @- << EOF
|
||||
{
|
||||
"cinema_floor_auditorium": [ [ [1,2], [6,7] ], [ [3,5], [8,9] ] ]
|
||||
}
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/movies?id=eq.1" \
|
||||
-X PATCH -H "Content-Type: application/json" \
|
||||
-d @- << EOF
|
||||
{
|
||||
"cinema_floor_auditorium": [ [ [1,2], [6,7] ], [ [3,5], [8,9] ] ]
|
||||
}
|
||||
EOF
|
||||
EOF
|
||||
|
||||
Then, for example, to query the auditoriums that are located in the first cinema (position 0 in the array) and on the second floor (position 1 in the next inner array), we can use the arrow operators this way:
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
GET /movies?select=title,auditorium:cinema_floor_auditorium->0->1&id=eq.1 HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/movies?select=title,auditorium:cinema_floor_auditorium->0->1&id=eq.1"
|
||||
curl "http://localhost:3000/movies?select=title,auditorium:cinema_floor_auditorium->0->1&id=eq.1"
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
@@ -262,211 +97,6 @@ Then, for example, to query the auditoriums that are located in the first cinema
|
||||
}
|
||||
]
|
||||
|
||||
Composite Types
|
||||
---------------
|
||||
|
||||
With PostgREST, you have two options to handle `composite type columns <https://www.postgresql.org/docs/current/rowtypes.html>`_.
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
create type dimension as (
|
||||
length decimal(6,2),
|
||||
width decimal (6,2),
|
||||
height decimal (6,2),
|
||||
unit text
|
||||
);
|
||||
|
||||
create table products (
|
||||
id int primary key,
|
||||
size dimension
|
||||
);
|
||||
|
||||
insert into products (id, size)
|
||||
values (1, '(5.0,5.0,10.0,"cm")');
|
||||
|
||||
On one hand you can insert values using string representation.
|
||||
|
||||
.. tabs::
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
POST /products HTTP/1.1
|
||||
Content-Type: application/json
|
||||
|
||||
{ "id": 2, "size": "(0.7,0.5,1.8,\"m\")" }
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/products" \
|
||||
-X POST -H "Content-Type: application/json" \
|
||||
-d @- << EOF
|
||||
{ "id": 2, "size": "(0.7,0.5,1.8,\"m\")" }
|
||||
EOF
|
||||
|
||||
Or you could insert the same data in JSON format.
|
||||
|
||||
.. tabs::
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
POST /products HTTP/1.1
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"id": 2,
|
||||
"size": {
|
||||
"length": 0.7,
|
||||
"width": 0.5,
|
||||
"height": 1.8,
|
||||
"unit": "m"
|
||||
}
|
||||
}
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/products" \
|
||||
-X POST -H "Content-Type: application/json" \
|
||||
-d @- << EOF
|
||||
{
|
||||
"id": 2,
|
||||
"size": {
|
||||
"length": 0.7,
|
||||
"width": 0.5,
|
||||
"height": 1.8,
|
||||
"unit": "m"
|
||||
}
|
||||
}
|
||||
EOF
|
||||
|
||||
You can also query the data using arrow operators. See :ref:`composite_array_columns`.
|
||||
|
||||
Ranges
|
||||
------
|
||||
|
||||
PostgREST allows you to handle `ranges <https://www.postgresql.org/docs/current/rangetypes.html>`_.
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
create table events (
|
||||
id int primary key,
|
||||
name text unique,
|
||||
duration tsrange
|
||||
);
|
||||
|
||||
To insert a new event, specify the ``duration`` value as a string representation of the ``tsrange`` type:
|
||||
|
||||
.. tabs::
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
POST /events HTTP/1.1
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"id": 1,
|
||||
"name": "New Year's Party",
|
||||
"duration": "['2022-12-31 11:00','2023-01-01 06:00']"
|
||||
}
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/events" \
|
||||
-X POST -H "Content-Type: application/json" \
|
||||
-d @- << EOF
|
||||
{
|
||||
"id": 1,
|
||||
"name": "New Year's Party",
|
||||
"duration": "['2022-12-31 11:00','2023-01-01 06:00']"
|
||||
}
|
||||
EOF
|
||||
|
||||
You can use range :ref:`operators <operators>` to filter the data. But, in this case, requesting a filter like ``events?duration=cs.2023-01-01`` will return an error, because PostgreSQL needs an explicit cast from string to timestamp. A workaround is to use a range starting and ending in the same date:
|
||||
|
||||
.. tabs::
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
GET /events?duration=cs.[2023-01-01,2023-01-01] HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/events?duration=cs.\[2023-01-01,2023-01-01\]"
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
[
|
||||
{
|
||||
"id": 1,
|
||||
"name": "New Year's Party",
|
||||
"duration": "[\"2022-12-31 11:00:00\",\"2023-01-01 06:00:00\"]"
|
||||
}
|
||||
]
|
||||
|
||||
.. _casting_range_to_json:
|
||||
|
||||
Casting a Range to a JSON Object
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
As you may have noticed, the ``tsrange`` value is returned as a string literal. To return it as a JSON value, first you need to create a function that will do the conversion from a ``tsrange`` type:
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
create or replace function tsrange_to_json(tsrange) returns json as $$
|
||||
select json_build_object(
|
||||
'lower', lower($1)
|
||||
, 'upper', upper($1)
|
||||
, 'lower_inc', lower_inc($1)
|
||||
, 'upper_inc', upper_inc($1)
|
||||
);
|
||||
$$ language sql;
|
||||
|
||||
Then, create the cast using this function:
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
create cast (tsrange as json) with function tsrange_to_json(tsrange) as assignment;
|
||||
|
||||
Finally, do the request :ref:`casting the range column <casting_columns>`:
|
||||
|
||||
.. tabs::
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
GET /events?select=id,name,duration::json HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/events?select=id,name,duration::json"
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
[
|
||||
{
|
||||
"id": 1,
|
||||
"name": "New Year's Party",
|
||||
"duration": {
|
||||
"lower": "2022-12-31T11:00:00",
|
||||
"upper": "2023-01-01T06:00:00",
|
||||
"lower_inc": true,
|
||||
"upper_inc": true
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
.. note::
|
||||
|
||||
If you don't want to modify casts for built-in types, an option would be to `create a custom type <https://www.postgresql.org/docs/current/sql-createtype.html>`_
|
||||
for your own ``tsrange`` and add its own cast.
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
create type mytsrange as range (subtype = timestamp, subtype_diff = tsrange_subdiff);
|
||||
|
||||
-- define column types and casting function analogously to the above example
|
||||
-- ...
|
||||
|
||||
create cast (mytsrange as json) with function mytsrange_to_json(mytsrange) as assignment;
|
||||
|
||||
Bytea
|
||||
-----
|
||||
|
||||
@@ -491,49 +121,26 @@ Let's download the PostgREST logo for our test.
|
||||
|
||||
Now, to send the file ``postgrest-logo.png`` we need to set the ``Content-Type: application/octet-stream`` header in the request:
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
curl "http://localhost:3000/rpc/upload_binary" \
|
||||
-X POST -H "Content-Type: application/octet-stream" \
|
||||
--data-binary "@postgrest-logo.png"
|
||||
|
||||
POST /rpc/upload_binary HTTP/1.1
|
||||
Content-Type: application/octet-stream
|
||||
To get the image from the database, use :ref:`custom_media` like so:
|
||||
|
||||
postgrest-logo.png
|
||||
.. code-block:: postgres
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
create domain "image/png" as bytea;
|
||||
|
||||
curl "http://localhost:3000/rpc/upload_binary" \
|
||||
-X POST -H "Content-Type: application/octet-stream" \
|
||||
--data-binary "@postgrest-logo.png"
|
||||
create or replace get_image(id int) returns "image/png" as $$
|
||||
select file from files where id = $1;
|
||||
$$ language sql;
|
||||
|
||||
To get the image from the database, set the ``Accept: application/octet-stream`` header and select only the
|
||||
``bytea`` type column.
|
||||
.. code-block:: bash
|
||||
|
||||
.. tabs::
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
GET /files?select=file&id=eq.1 HTTP/1.1
|
||||
Accept: application/octet-stream
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/files?select=file&id=eq.1" \
|
||||
-H "Accept: application/octet-stream"
|
||||
|
||||
Use more accurate headers according to the type of the files by using the :ref:`raw-media-types` configuration. For example, adding the ``raw-media-types="image/png"`` setting to the configuration file will allow you to use the ``Accept: image/png`` header:
|
||||
|
||||
.. tabs::
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
GET /files?select=file&id=eq.1 HTTP/1.1
|
||||
Accept: image/png
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/files?select=file&id=eq.1" \
|
||||
-H "Accept: image/png"
|
||||
curl "http://localhost:3000/get_image?id=1" \
|
||||
-H "Accept: image/png"
|
||||
|
||||
See :ref:`providing_img` for a step-by-step example on how to handle images in HTML.
|
||||
|
||||
@@ -541,6 +148,104 @@ See :ref:`providing_img` for a step-by-step example on how to handle images in H
|
||||
|
||||
Be careful when saving binaries in the database, having a separate storage service for these is preferable in most cases. See `Storing Binary files in the Database <https://wiki.postgresql.org/wiki/BinaryFilesInDB>`_.
|
||||
|
||||
Composite Types
|
||||
---------------
|
||||
|
||||
With PostgREST, you have two options to handle `composite type columns <https://www.postgresql.org/docs/current/rowtypes.html>`_.
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
create type dimension as (
|
||||
length decimal(6,2),
|
||||
width decimal (6,2),
|
||||
height decimal (6,2),
|
||||
unit text
|
||||
);
|
||||
|
||||
create table products (
|
||||
id int primary key,
|
||||
size dimension
|
||||
);
|
||||
|
||||
insert into products (id, size)
|
||||
values (1, '(5.0,5.0,10.0,"cm")');
|
||||
|
||||
On one hand you can insert values using string representation.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3000/products" \
|
||||
-X POST -H "Content-Type: application/json" \
|
||||
-d @- << EOF
|
||||
{ "id": 2, "size": "(0.7,0.5,1.8,\"m\")" }
|
||||
EOF
|
||||
|
||||
Or you could insert the same data in JSON format.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3000/products" \
|
||||
-X POST -H "Content-Type: application/json" \
|
||||
-d @- << EOF
|
||||
{
|
||||
"id": 2,
|
||||
"size": {
|
||||
"length": 0.7,
|
||||
"width": 0.5,
|
||||
"height": 1.8,
|
||||
"unit": "m"
|
||||
}
|
||||
}
|
||||
EOF
|
||||
|
||||
You can also query the data using arrow operators. See :ref:`composite_array_columns`.
|
||||
|
||||
Enums
|
||||
-----
|
||||
|
||||
You can handle `Enumerated Types <https://www.postgresql.org/docs/current/datatype-enum.html>`_ using string representations:
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
create type letter_size as enum ('s','m','l','xl');
|
||||
|
||||
create table products (
|
||||
id int primary key generated always as identity,
|
||||
name text,
|
||||
size letter_size
|
||||
);
|
||||
|
||||
To insert or update the value use a string:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl -X POST "http://localhost:3000/products" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d @- << EOF
|
||||
{ "name": "t-shirt", "size": "l" }
|
||||
EOF
|
||||
|
||||
You can then query and filter the enum using the compatible :ref:`operators <operators>`.
|
||||
For example, to get all the products larger than `m` and ordering them by their size:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3000/products?select=name,size&size=gt.m&order=size"
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
[
|
||||
{
|
||||
"name": "t-shirt",
|
||||
"size": "l"
|
||||
},
|
||||
{
|
||||
"name": "hoodie",
|
||||
"size": "xl"
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
hstore
|
||||
------
|
||||
|
||||
@@ -558,53 +263,67 @@ You can work with data types belonging to additional supplied modules such as `h
|
||||
|
||||
The ``name`` column will have the name of the country in different formats. You can insert values using the string representation for that data type:
|
||||
|
||||
.. tabs::
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
POST /countries HTTP/1.1
|
||||
Content-Type: application/json
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3000/countries" \
|
||||
-X POST -H "Content-Type: application/json" \
|
||||
-d @- << EOF
|
||||
[
|
||||
{ "id": 1, "name": "common => Egypt, official => \"Arab Republic of Egypt\", native => مصر" },
|
||||
{ "id": 2, "name": "common => Germany, official => \"Federal Republic of Germany\", native => Deutschland" }
|
||||
]
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/countries" \
|
||||
-X POST -H "Content-Type: application/json" \
|
||||
-d @- << EOF
|
||||
[
|
||||
{ "id": 1, "name": "common => Egypt, official => \"Arab Republic of Egypt\", native => مصر" },
|
||||
{ "id": 2, "name": "common => Germany, official => \"Federal Republic of Germany\", native => Deutschland" }
|
||||
]
|
||||
EOF
|
||||
EOF
|
||||
|
||||
Notice that the use of ``"`` in the value of the ``name`` column needs to be escaped using a backslash ``\``.
|
||||
|
||||
You can also query and filter the value of a ``hstore`` column using the arrow operators, as you would do for a :ref:`JSON column<json_columns>`. For example, if you want to get the native name of Egypt:
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
GET /countries?select=name->>native&name->>common=like.Egypt HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/countries?select=name->>native&name->>common=like.Egypt"
|
||||
curl "http://localhost:3000/countries?select=name->>native&name->>common=like.Egypt"
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
[{ "native": "مصر" }]
|
||||
|
||||
JSON
|
||||
----
|
||||
|
||||
To work with a ``json`` type column, you can handle the value as a JSON object.
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
create table products (
|
||||
id int primary key,
|
||||
name text unique,
|
||||
extra_info json
|
||||
);
|
||||
|
||||
You can insert a new product using a JSON object for the ``extra_info`` column:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3000/products" \
|
||||
-X POST -H "Content-Type: application/json" \
|
||||
-d @- << EOF
|
||||
{
|
||||
"id": 1,
|
||||
"name": "Canned fish",
|
||||
"extra_info": {
|
||||
"expiry_date": "2025-12-31",
|
||||
"exportable": true
|
||||
}
|
||||
}
|
||||
EOF
|
||||
|
||||
To query and filter the data see :ref:`json_columns` for a complete reference.
|
||||
|
||||
.. _ww_postgis:
|
||||
|
||||
PostGIS
|
||||
-------
|
||||
|
||||
You can use the string representation for `PostGIS <https://postgis.net/>`_ data types such as ``geometry`` or ``geography`` (you need to `install PostGIS <https://postgis.net/install/>`_ first).
|
||||
You can use the string representation for `PostGIS <https://postgis.net/>`_ data types such as ``geometry`` or ``geography`` (you need to `install PostGIS <https://postgis.net/documentation/getting_started/>`_ first).
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
@@ -619,42 +338,23 @@ You can use the string representation for `PostGIS <https://postgis.net/>`_ data
|
||||
|
||||
To add areas in polygon format, you can use string representation:
|
||||
|
||||
.. tabs::
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
POST /coverage HTTP/1.1
|
||||
Content-Type: application/json
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3000/coverage" \
|
||||
-X POST -H "Content-Type: application/json" \
|
||||
-d @- << EOF
|
||||
[
|
||||
{ "id": 1, "name": "small", "area": "SRID=4326;POLYGON((0 0, 1 0, 1 1, 0 1, 0 0))" },
|
||||
{ "id": 2, "name": "big", "area": "SRID=4326;POLYGON((0 0, 10 0, 10 10, 0 10, 0 0))" }
|
||||
]
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/coverage" \
|
||||
-X POST -H "Content-Type: application/json" \
|
||||
-d @- << EOF
|
||||
[
|
||||
{ "id": 1, "name": "small", "area": "SRID=4326;POLYGON((0 0, 1 0, 1 1, 0 1, 0 0))" },
|
||||
{ "id": 2, "name": "big", "area": "SRID=4326;POLYGON((0 0, 10 0, 10 10, 0 10, 0 0))" }
|
||||
]
|
||||
EOF
|
||||
EOF
|
||||
|
||||
Now, when you request the information, PostgREST will automatically cast the ``area`` column into a ``Polygon`` geometry type. Although this is useful, you may need the whole output to be in `GeoJSON <https://geojson.org/>`_ format out of the box, which can be done by including the ``Accept: application/geo+json`` in the request. This will work for PostGIS versions 3.0.0 and up and will return the output as a `FeatureCollection Object <https://www.rfc-editor.org/rfc/rfc7946#section-3.3>`_:
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
GET /coverage HTTP/1.1
|
||||
Accept: application/geo+json
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/coverage" \
|
||||
-H "Accept: application/geo+json"
|
||||
curl "http://localhost:3000/coverage" \
|
||||
-H "Accept: application/geo+json"
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
@@ -718,15 +418,9 @@ In the case that you are using older PostGIS versions, then creating a function
|
||||
|
||||
Now this query will return the same results:
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
GET /rpc/coverage_geo_collection HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/rpc/coverage_geo_collection"
|
||||
curl "http://localhost:3000/rpc/coverage_geo_collection"
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
@@ -761,3 +455,157 @@ Now this query will return the same results:
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
Ranges
|
||||
------
|
||||
|
||||
PostgREST allows you to handle `ranges <https://www.postgresql.org/docs/current/rangetypes.html>`_.
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
create table events (
|
||||
id int primary key,
|
||||
name text unique,
|
||||
duration tsrange
|
||||
);
|
||||
|
||||
To insert a new event, specify the ``duration`` value as a string representation of the ``tsrange`` type:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3000/events" \
|
||||
-X POST -H "Content-Type: application/json" \
|
||||
-d @- << EOF
|
||||
{
|
||||
"id": 1,
|
||||
"name": "New Year's Party",
|
||||
"duration": "['2022-12-31 11:00','2023-01-01 06:00']"
|
||||
}
|
||||
EOF
|
||||
|
||||
You can use range :ref:`operators <operators>` to filter the data. But, in this case, requesting a filter like ``events?duration=cs.2023-01-01`` will return an error, because PostgreSQL needs an explicit cast from string to timestamp. A workaround is to use a range starting and ending in the same date:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3000/events?duration=cs.\[2023-01-01,2023-01-01\]"
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
[
|
||||
{
|
||||
"id": 1,
|
||||
"name": "New Year's Party",
|
||||
"duration": "[\"2022-12-31 11:00:00\",\"2023-01-01 06:00:00\"]"
|
||||
}
|
||||
]
|
||||
|
||||
.. _casting_range_to_json:
|
||||
|
||||
Casting a Range to a JSON Object
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
As you may have noticed, the ``tsrange`` value is returned as a string literal. To return it as a JSON value, first you need to create a function that will do the conversion from a ``tsrange`` type:
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
create or replace function tsrange_to_json(tsrange) returns json as $$
|
||||
select json_build_object(
|
||||
'lower', lower($1)
|
||||
, 'upper', upper($1)
|
||||
, 'lower_inc', lower_inc($1)
|
||||
, 'upper_inc', upper_inc($1)
|
||||
);
|
||||
$$ language sql;
|
||||
|
||||
Then, create the cast using this function:
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
create cast (tsrange as json) with function tsrange_to_json(tsrange) as assignment;
|
||||
|
||||
Finally, do the request :ref:`casting the range column <casting_columns>`:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3000/events?select=id,name,duration::json"
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
[
|
||||
{
|
||||
"id": 1,
|
||||
"name": "New Year's Party",
|
||||
"duration": {
|
||||
"lower": "2022-12-31T11:00:00",
|
||||
"upper": "2023-01-01T06:00:00",
|
||||
"lower_inc": true,
|
||||
"upper_inc": true
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
.. note::
|
||||
|
||||
If you don't want to modify casts for built-in types, an option would be to `create a custom type <https://www.postgresql.org/docs/current/sql-createtype.html>`_
|
||||
for your own ``tsrange`` and add its own cast.
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
create type mytsrange as range (subtype = timestamp, subtype_diff = tsrange_subdiff);
|
||||
|
||||
-- define column types and casting function analogously to the above example
|
||||
-- ...
|
||||
|
||||
create cast (mytsrange as json) with function mytsrange_to_json(mytsrange) as assignment;
|
||||
|
||||
Timestamps
|
||||
----------
|
||||
|
||||
You can use the **time zone** to filter or send data if needed.
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
create table reports (
|
||||
id int primary key
|
||||
, due_date timestamptz
|
||||
);
|
||||
|
||||
Suppose you are located in Sydney and want create a report with the date in the local time zone. Your request should look like this:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3000/reports" \
|
||||
-X POST -H "Content-Type: application/json" \
|
||||
-d '[{ "id": 1, "due_date": "2022-02-24 11:10:15 Australia/Sydney" },{ "id": 2, "due_date": "2022-02-27 22:00:00 Australia/Sydney" }]'
|
||||
|
||||
Someone located in Cairo can retrieve the data using their local time, too:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3000/reports?due_date=eq.2022-02-24+02:10:15+Africa/Cairo"
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
[
|
||||
{
|
||||
"id": 1,
|
||||
"due_date": "2022-02-23T19:10:15-05:00"
|
||||
}
|
||||
]
|
||||
|
||||
The response has the date in the time zone configured by the server: ``UTC -05:00`` (see :ref:`prefer_timezone`).
|
||||
|
||||
You can use other comparative filters and also all the `PostgreSQL special date/time input values <https://www.postgresql.org/docs/current/datatype-datetime.html#DATATYPE-DATETIME-SPECIAL-TABLE>`_ as illustrated in this example:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3000/reports?or=(and(due_date.gte.today,due_date.lte.tomorrow),and(due_date.gt.-infinity,due_date.lte.epoch))"
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
[
|
||||
{
|
||||
"id": 2,
|
||||
"due_date": "2022-02-27T06:00:00-05:00"
|
||||
}
|
||||
]
|
||||
|
||||
@@ -5,7 +5,7 @@ PostgREST Documentation
|
||||
|
||||
.. container:: image-container
|
||||
|
||||
.. figure:: _static/logo.png
|
||||
.. figure:: ../static/postgrest.png
|
||||
|
||||
.. image:: https://img.shields.io/github/stars/postgrest/postgrest.svg?style=social
|
||||
:target: https://github.com/PostgREST/postgrest
|
||||
@@ -28,30 +28,59 @@ Sponsors
|
||||
|
||||
.. container:: image-container
|
||||
|
||||
.. image:: _static/cybertec-new.png
|
||||
:target: https://www.cybertec-postgresql.com/en/?utm_source=postgrest.org&utm_medium=referral&utm_campaign=postgrest
|
||||
:width: 13em
|
||||
.. container:: img-dark
|
||||
|
||||
.. image:: _static/gnuhost.png
|
||||
:target: https://euronodes.com/?utm_source=sponsor&utm_campaign=postgrest
|
||||
:width: 13em
|
||||
.. image:: ../static/cybertec-dark.svg
|
||||
:target: https://www.cybertec-postgresql.com/en/?utm_source=postgrest.org&utm_medium=referral&utm_campaign=postgrest
|
||||
|
||||
.. container:: img-light
|
||||
|
||||
.. image:: ../static/cybertec.svg
|
||||
:target: https://www.cybertec-postgresql.com/en/?utm_source=postgrest.org&utm_medium=referral&utm_campaign=postgrest
|
||||
|
||||
.. image:: ../static/gnuhost.png
|
||||
:target: https://gnuhost.eu/?utm_source=sponsor&utm_campaign=postgrest
|
||||
|
||||
.. container:: img-dark
|
||||
|
||||
.. image:: ../static/neon-dark.jpg
|
||||
:target: https://neon.tech/?utm_source=sponsor&utm_campaign=postgrest
|
||||
|
||||
.. container:: img-light
|
||||
|
||||
.. image:: ../static/neon.jpg
|
||||
:target: https://neon.tech/?utm_source=sponsor&utm_campaign=postgrest
|
||||
|
||||
|
|
||||
|
||||
.. image:: _static/supabase.png
|
||||
:target: https://supabase.com/?utm_source=postgrest%20backers&utm_medium=open%20source%20partner&utm_campaign=postgrest%20backers%20github&utm_term=homepage
|
||||
:width: 13em
|
||||
.. container:: img-dark
|
||||
|
||||
.. image:: _static/neon.jpg
|
||||
:target: https://neon.tech/?utm_source=sponsor&utm_campaign=postgrest
|
||||
:width: 13em
|
||||
.. image:: ../static/code-build-dark.png
|
||||
:target: https://code.build/?utm_source=sponsor&utm_campaign=postgrest
|
||||
|
||||
.. container:: img-light
|
||||
|
||||
.. image:: ../static/code-build.png
|
||||
:target: https://code.build/?utm_source=sponsor&utm_campaign=postgrest
|
||||
|
||||
.. container:: img-dark
|
||||
|
||||
.. image:: ../static/supabase-dark.png
|
||||
:target: https://supabase.com/?utm_source=postgrest%20backers&utm_medium=open%20source%20partner&utm_campaign=postgrest%20backers%20github&utm_term=homepage
|
||||
|
||||
.. container:: img-light
|
||||
|
||||
.. image:: ../static/supabase.png
|
||||
:target: https://supabase.com/?utm_source=postgrest%20backers&utm_medium=open%20source%20partner&utm_campaign=postgrest%20backers%20github&utm_term=homepage
|
||||
|
||||
.. image:: ../static/tembo.png
|
||||
:target: https://tembo.io/?utm_source=sponsor&utm_campaign=postgrest
|
||||
|
||||
.. The static/empty.png(created with `convert -size 320x95 xc:#fcfcfc empty.png`) is an ugly workaround
|
||||
to create space and center the logos. It's not easy to layout with restructuredText.
|
||||
|
||||
.. .. image:: _static/empty.png
|
||||
:target: #sponsors
|
||||
:width: 13em
|
||||
|
||||
|
|
||||
|
||||
@@ -80,13 +109,10 @@ Getting Support
|
||||
|
||||
The project has a friendly and growing community. For discussions, use the Github `discussions page <https://github.com/PostgREST/postgrest/discussions>`_. You can also report or search for bugs/features on the Github `issues <https://github.com/PostgREST/postgrest/issues>`_ page.
|
||||
|
||||
.. toctree::
|
||||
:glob:
|
||||
:caption: Release Notes
|
||||
:reversed:
|
||||
:maxdepth: 1
|
||||
Release Notes
|
||||
-------------
|
||||
|
||||
releases/*
|
||||
The release notes are published on `PostgREST's GitHub release page <https://github.com/PostgREST/postgrest/releases>`_.
|
||||
|
||||
Tutorials
|
||||
---------
|
||||
@@ -115,11 +141,13 @@ Technical references for PostgREST's functionality.
|
||||
|
||||
references/auth.rst
|
||||
references/api.rst
|
||||
references/cli.rst
|
||||
references/transactions.rst
|
||||
references/connection_pool.rst
|
||||
references/schema_cache.rst
|
||||
references/errors.rst
|
||||
references/configuration.rst
|
||||
references/observability.rst
|
||||
references/*
|
||||
|
||||
Explanations
|
||||
@@ -184,12 +212,19 @@ Here are some companies that use PostgREST in production.
|
||||
* `Datrium <https://www.datrium.com>`_
|
||||
* `Drip Depot <https://www.dripdepot.com>`_
|
||||
* `Image-charts <https://www.image-charts.com>`_
|
||||
* `Moat <https://www.oracle.com/advertising/>`_
|
||||
* `Netwo <https://www.netwo.io>`_
|
||||
* `Nimbus <https://www.nimbusforwork.com>`_
|
||||
* `Nimbus <https://www.nimbusfacility.com/sg/home>`_
|
||||
- See how Nimbus uses PostgREST in `Paul Copplestone's blog post <https://paul.copplest.one/blog/nimbus-tech-2019-04.html>`_.
|
||||
* `OpenBooking <https://www.openbooking.ch>`_
|
||||
* `OpenBooking <https://openbooking.ch>`_
|
||||
* `Redsmin <https://www.redsmin.com>`_
|
||||
* `Sompani <https://www.sompani.com>`_
|
||||
* `Supabase <https://supabase.com>`_
|
||||
|
||||
.. Failing links
|
||||
* `eGull <http://www.egull.co>`_
|
||||
* `MotionDynamic - Fast highly dynamic video generation at scale <https://motiondynamic.tech>`_
|
||||
|
||||
Testimonials
|
||||
------------
|
||||
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
Greenplum
|
||||
#########
|
||||
|
||||
`Greenplum <https://greenplum.org/>`_ has been reported to work by adding ``LOGIN`` to the :ref:`anonymous and user roles <roles>`.
|
||||
|
||||
For more details, see https://github.com/PostgREST/postgrest/issues/2021.
|
||||
@@ -1,122 +0,0 @@
|
||||
.. _deploy_heroku:
|
||||
|
||||
Heroku
|
||||
======
|
||||
|
||||
1. Log into Heroku using the `Heroku CLI <https://devcenter.heroku.com/articles/heroku-cli>`_:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
# If you have multiple Heroku accounts, use flag '--interactive' to switch between them
|
||||
heroku login --interactive
|
||||
|
||||
|
||||
2. Create a new Heroku app using the PostgREST buildpack:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
mkdir ${YOUR_APP_NAME}
|
||||
cd ${YOUR_APP_NAME}
|
||||
git init .
|
||||
|
||||
heroku apps:create ${YOUR_APP_NAME} --buildpack https://github.com/PostgREST/postgrest-heroku.git
|
||||
heroku git:remote -a ${YOUR_APP_NAME}
|
||||
|
||||
3. Create a new Heroku PostgreSQL add-on attached to the app and keep notes of the assigned add-on name (e.g. :code:`postgresql-curly-58902`) referred later as ${HEROKU_PG_DB_NAME}
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
heroku addons:create heroku-postgresql:standard-0 -a ${YOUR_APP_NAME}
|
||||
# wait until the add-on is available
|
||||
heroku pg:wait -a ${YOUR_APP_NAME}
|
||||
|
||||
4. Create the necessary user roles according to the
|
||||
`PostgREST documentation <https://postgrest.org/en/stable/auth.html>`_:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
heroku pg:credentials:create --name api_user -a ${YOUR_APP_NAME}
|
||||
# use the following command to ensure the new credential state is active before attaching it
|
||||
heroku pg:credentials -a ${YOUR_APP_NAME}
|
||||
|
||||
heroku addons:attach ${HEROKU_PG_DB_NAME} --credential api_user -a ${YOUR_APP_NAME}
|
||||
|
||||
5. Connect to the PostgreSQL database and create some sample data:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
heroku psql -a ${YOUR_APP_NAME}
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
# from the psql command prompt execute the following commands:
|
||||
create schema api;
|
||||
|
||||
create table api.todos (
|
||||
id serial primary key,
|
||||
done boolean not null default false,
|
||||
task text not null,
|
||||
due timestamptz
|
||||
);
|
||||
|
||||
insert into api.todos (task) values
|
||||
('finish tutorial 0'), ('pat self on back');
|
||||
|
||||
grant usage on schema api to api_user;
|
||||
grant select on api.todos to api_user;
|
||||
|
||||
6. Create the :code:`Procfile`:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
web: PGRST_SERVER_HOST=0.0.0.0 PGRST_SERVER_PORT=${PORT} PGRST_DB_URI=${PGRST_DB_URI:-${DATABASE_URL}} ./postgrest-${POSTGREST_VER}
|
||||
..
|
||||
|
||||
Set the following environment variables on Heroku:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
heroku config:set POSTGREST_VER=10.0.0
|
||||
heroku config:set PGRST_DB_SCHEMA=api
|
||||
heroku config:set PGRST_DB_ANON_ROLE=api_user
|
||||
..
|
||||
|
||||
PGRST_DB_URI can be set if an external database is used or if it's different from the default Heroku DATABASE_URL. This latter is used if nothing is provided.
|
||||
POSTGREST_VER is mandatory to select and build the required PostgREST release.
|
||||
|
||||
See https://postgrest.org/en/stable/configuration.html#environment-variables for the full list of environment variables.
|
||||
|
||||
7. Build and deploy your app:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
git add Procfile
|
||||
git commit -m "PostgREST on Heroku"
|
||||
git push heroku master
|
||||
..
|
||||
|
||||
Your Heroku app should be live at :code:`${YOUR_APP_NAME}.herokuapp.com`
|
||||
|
||||
8. Test your app
|
||||
|
||||
From a terminal display the application logs:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
heroku logs -t
|
||||
..
|
||||
|
||||
From a different terminal retrieve with curl the records previously created:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl https://${YOUR_APP_NAME}.herokuapp.com/todos
|
||||
..
|
||||
|
||||
and test that any attempt to modify the table via a read-only user is not allowed:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl https://${YOUR_APP_NAME}.herokuapp.com/todos -X POST \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"task": "do bad thing"}'
|
||||
@@ -9,23 +9,3 @@ JWT from Auth0
|
||||
An external service like `Auth0 <https://auth0.com/>`_ can do the hard work transforming OAuth from Github, Twitter, Google etc into a JWT suitable for PostgREST. Auth0 can also handle email signup and password reset flows.
|
||||
|
||||
To use Auth0, create `an application <https://auth0.com/docs/get-started/applications>`_ for your app and `an API <https://auth0.com/docs/get-started/apis>`_ for your PostgREST server. Auth0 supports both HS256 and RS256 scheme for the issued tokens for APIs. For simplicity, you may first try HS256 scheme while creating your API on Auth0. Your application should use your PostgREST API's `API identifier <https://auth0.com/docs/get-started/apis/api-settings>`_ by setting it with the `audience parameter <https://auth0.com/docs/secure/tokens/access-tokens/get-access-tokens#control-access-token-audience>`_ during the authorization request. This will ensure that Auth0 will issue an access token for your PostgREST API. For PostgREST to verify the access token, you will need to set ``jwt-secret`` on PostgREST config file with your API's signing secret.
|
||||
|
||||
.. note::
|
||||
|
||||
Our code requires a database role in the JWT. To add it you need to save the database role in Auth0 `app metadata <https://auth0.com/docs/manage-users/user-accounts/metadata/manage-metadata-rules>`_. Then, you will need to write `a rule <https://auth0.com/docs/customize/rules>`_ that will extract the role from the user's app_metadata and set it as a `custom claim <https://auth0.com/docs/get-started/apis/scopes/sample-use-cases-scopes-and-claims#add-custom-claims-to-a-token>`_ in the access token. Note that, you may use Auth0's `core authorization feature <https://auth0.com/docs/manage-users/access-control/rbac>`_ for more complex use cases. Metadata solution is mentioned here for simplicity.
|
||||
|
||||
.. code:: javascript
|
||||
|
||||
function (user, context, callback) {
|
||||
|
||||
// Follow the documentations at
|
||||
// https://postgrest.org/en/latest/configuration.html#db-role-claim-key
|
||||
// to set a custom role claim on PostgREST
|
||||
// and use it as custom claim attribute in this rule
|
||||
const myRoleClaim = 'https://myapp.com/role';
|
||||
|
||||
user.app_metadata = user.app_metadata || {};
|
||||
context.accessToken[myRoleClaim] = user.app_metadata.role;
|
||||
callback(null, user, context);
|
||||
}
|
||||
|
||||
|
||||
@@ -8,27 +8,15 @@ Block Full-Table Operations
|
||||
|
||||
If the :ref:`active role <user_impersonation>` can delete table rows then the DELETE verb is allowed for clients. Here's an API request to delete old rows from a hypothetical logs table:
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
DELETE /logs?time=lt.1991-08-06 HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/logs?time=lt.1991-08-06" -X DELETE
|
||||
curl "http://localhost:3000/logs?time=lt.1991-08-06" -X DELETE
|
||||
|
||||
Note that it's very easy to delete the **entire table** by omitting the query parameter!
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
DELETE /logs HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/logs" -X DELETE
|
||||
curl "http://localhost:3000/logs" -X DELETE
|
||||
|
||||
This can happen accidentally such as by switching a request from a GET to a DELETE. To protect against accidental operations use the `pg-safeupdate <https://github.com/eradman/pg-safeupdate>`_ PostgreSQL extension. It raises an error if UPDATE or DELETE are executed without specifying conditions. To install it you can use the `PGXN <https://pgxn.org/>`_ network:
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
systemd
|
||||
=======
|
||||
|
||||
For Linux distributions that use **systemd** (Ubuntu, Debian, Archlinux) you can create a daemon in the following way.
|
||||
For Linux distributions that use **systemd** (Ubuntu, Debian, Arch Linux) you can create a daemon in the following way.
|
||||
|
||||
First, create postgrest configuration in ``/etc/postgrest/config``
|
||||
|
||||
@@ -12,6 +12,12 @@ First, create postgrest configuration in ``/etc/postgrest/config``
|
||||
db-anon-role = "<your_anon_role>"
|
||||
jwt-secret = "<your_secret>"
|
||||
|
||||
Create a dedicated ``postgrest`` user with:
|
||||
|
||||
.. code-block:: ini
|
||||
|
||||
sudo useradd -M -U -d /nonexistent -s /usr/sbin/nologin postgrest
|
||||
|
||||
Then create the systemd service file in ``/etc/systemd/system/postgrest.service``
|
||||
|
||||
.. code-block:: ini
|
||||
@@ -21,6 +27,8 @@ Then create the systemd service file in ``/etc/systemd/system/postgrest.service`
|
||||
After=postgresql.service
|
||||
|
||||
[Service]
|
||||
User=postgrest
|
||||
Group=postgrest
|
||||
ExecStart=/bin/postgrest /etc/postgrest/config
|
||||
ExecReload=/bin/kill -SIGUSR1 $MAINPID
|
||||
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
from livereload import Server, shell
|
||||
from subprocess import call
|
||||
|
||||
## Build docs at startup
|
||||
call(["sphinx-build", "-b", "html", "-a", "-n", ".", "_build"])
|
||||
server = Server()
|
||||
server.watch("**/*.rst", shell("sphinx-build -b html -a -n . _build"))
|
||||
# For custom port and host
|
||||
# server.serve(root='_build/', host='192.168.1.2')
|
||||
server.serve(root="_build/")
|
||||
@@ -1,63 +1,60 @@
|
||||
personal_ws-1.1 en 0 utf-8
|
||||
api
|
||||
API's
|
||||
APIs
|
||||
APISIX
|
||||
Archlinux
|
||||
aud
|
||||
Auth
|
||||
auth
|
||||
authenticator
|
||||
backoff
|
||||
balancer
|
||||
booleans
|
||||
Bouscal
|
||||
buildpack
|
||||
BOM
|
||||
Bytea
|
||||
Cardano
|
||||
casted
|
||||
cd
|
||||
centric
|
||||
changelog
|
||||
CLI
|
||||
coercible
|
||||
conf
|
||||
Cloudflare
|
||||
config
|
||||
cors
|
||||
CORS
|
||||
CPUs
|
||||
cryptographically
|
||||
CSV
|
||||
durations
|
||||
DDL
|
||||
DOM
|
||||
DevOps
|
||||
DiBiase
|
||||
dockerize
|
||||
enum
|
||||
Enums
|
||||
eq
|
||||
ETH
|
||||
Ethereum
|
||||
EveryLayout
|
||||
Fenko
|
||||
Fernandes
|
||||
filename
|
||||
FreeBSD
|
||||
fts
|
||||
GC
|
||||
GeoJSON
|
||||
GHC
|
||||
Github
|
||||
Google
|
||||
grantor
|
||||
GraphQL
|
||||
Greenplum
|
||||
gte
|
||||
GUC
|
||||
GUCs
|
||||
gucs
|
||||
Haskell
|
||||
Heroku
|
||||
HMAC
|
||||
htmx
|
||||
Htmx
|
||||
Homebrew
|
||||
hstore
|
||||
HTTP
|
||||
HTTPS
|
||||
HV
|
||||
Ibarluzea
|
||||
Inlining
|
||||
inlined
|
||||
Integrations
|
||||
@@ -84,6 +81,7 @@ logins
|
||||
lon
|
||||
lt
|
||||
lte
|
||||
macOS
|
||||
misprediction
|
||||
multi
|
||||
namespace
|
||||
@@ -96,14 +94,14 @@ npm
|
||||
nxl
|
||||
nxr
|
||||
OAuth
|
||||
Observability
|
||||
OpenAPI
|
||||
openapi
|
||||
ORM
|
||||
ov
|
||||
parametrized
|
||||
passphrase
|
||||
Pawel
|
||||
PBKDF
|
||||
Pelletier
|
||||
PgBouncer
|
||||
pgcrypto
|
||||
pgjwt
|
||||
@@ -117,7 +115,6 @@ phraseto
|
||||
plainto
|
||||
plfts
|
||||
poolers
|
||||
POSIX
|
||||
PostGIS
|
||||
PostgreSQL
|
||||
PostgreSQL's
|
||||
@@ -129,52 +126,43 @@ pre
|
||||
preflight
|
||||
plpgsql
|
||||
psql
|
||||
Qin
|
||||
RabbitMQ
|
||||
Rafaj
|
||||
RDS
|
||||
reallyreallyreallyreallyverysafe
|
||||
Rechkemmer
|
||||
Redux
|
||||
refactor
|
||||
reloadable
|
||||
Reloadable
|
||||
Remo
|
||||
requester's
|
||||
RESTful
|
||||
RLS
|
||||
RPC
|
||||
RSA
|
||||
Saleeba
|
||||
safeupdate
|
||||
savepoint
|
||||
schemas
|
||||
schema's
|
||||
Severin
|
||||
SHA
|
||||
Sommer
|
||||
signup
|
||||
SIGUSR
|
||||
sl
|
||||
spreaded
|
||||
Spreaded
|
||||
SQL
|
||||
sql
|
||||
SQLSTATE
|
||||
sr
|
||||
SSL
|
||||
stateful
|
||||
stdout
|
||||
Stolarz
|
||||
supervisees
|
||||
SvelteKit
|
||||
SwaggerUI
|
||||
syslog
|
||||
systemd
|
||||
todo
|
||||
todos
|
||||
tos
|
||||
Tsingson
|
||||
tsquery
|
||||
tx
|
||||
Tyll
|
||||
TypeScript
|
||||
UI
|
||||
ui
|
||||
@@ -182,6 +170,7 @@ unicode
|
||||
unikernel
|
||||
unix
|
||||
updatable
|
||||
unfulfillable
|
||||
Untyped
|
||||
UPSERT
|
||||
Upsert
|
||||
@@ -201,4 +190,3 @@ Websockets
|
||||
webuser
|
||||
wfts
|
||||
www
|
||||
Zac
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
.. _admin_server:
|
||||
|
||||
Admin Server
|
||||
############
|
||||
|
||||
PostgREST provides an admin server that can be enabled by setting :ref:`admin-server-port`.
|
||||
|
||||
.. _health_check:
|
||||
|
||||
Health Check
|
||||
============
|
||||
|
||||
You can enable a health check to verify if PostgREST is available for client requests. Also to check the status of its internal state.
|
||||
|
||||
Two endpoints ``live`` and ``ready`` will then be available.
|
||||
|
||||
.. important::
|
||||
|
||||
If you have a machine with multiple network interfaces and multiple PostgREST instances in the same port, you need to specify a unique :ref:`hostname <server-host>`
|
||||
in the configuration of each PostgREST instance for the health check to work correctly. Don't use the special values(``!4``, ``*``, etc) in this case because the health check
|
||||
could report a false positive.
|
||||
|
||||
Live
|
||||
----
|
||||
|
||||
The ``live`` endpoint verifies if PostgREST is running on its configured port. A request will return ``200 OK`` if PostgREST is alive or ``500`` otherwise.
|
||||
|
||||
For instance, to verify if PostgREST is running while the ``admin-server-port`` is set to ``3001``:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl -I "http://localhost:3001/live"
|
||||
|
||||
.. code-block:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
|
||||
Ready
|
||||
-----
|
||||
|
||||
Additionally to the ``live`` check, the ``ready`` endpoint checks the state of the :ref:`connection_pool` and the :ref:`schema_cache`. A request will return ``200 OK`` if both are good or ``503`` if not.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl -I "http://localhost:3001/ready"
|
||||
|
||||
.. code-block:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
|
||||
PostgREST will try to recover from the ``503`` state with :ref:`automatic_recovery`.
|
||||
|
||||
Metrics
|
||||
=======
|
||||
|
||||
Provides :ref:`metrics`.
|
||||
|
||||
Runtime Configuration
|
||||
=====================
|
||||
|
||||
Provides a ``config`` endpoint that returns the runtime :ref:`configuration`.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3001/config"
|
||||
|
||||
.. code-block::
|
||||
|
||||
db-aggregates-enabled = false
|
||||
db-anon-role = "web_anon"
|
||||
db-channel = "pgrst"
|
||||
db-channel-enabled = false
|
||||
...
|
||||
|
||||
Runtime Schema Cache
|
||||
====================
|
||||
|
||||
Provides the ``schema_cache`` endpoint that prints the runtime :ref:`schema_cache`.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3001/schema_cache"
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
{
|
||||
"dbMediaHandlers": ["..."],
|
||||
"dbRelationships": ["..."],
|
||||
"dbRepresentations": ["..."],
|
||||
"dbRoutines": ["..."],
|
||||
"dbTables": ["..."],
|
||||
"dbTimezones": ["..."]
|
||||
}
|
||||
@@ -3,20 +3,24 @@
|
||||
API
|
||||
###
|
||||
|
||||
PostgREST exposes three database objects of a schema as resources: tables, views and stored procedures.
|
||||
PostgREST exposes three database objects of a schema as resources: tables, views and functions.
|
||||
|
||||
.. toctree::
|
||||
:glob:
|
||||
:maxdepth: 1
|
||||
|
||||
api/tables_views.rst
|
||||
api/stored_procedures.rst
|
||||
api/functions.rst
|
||||
api/schemas.rst
|
||||
api/computed_fields.rst
|
||||
api/domain_representations.rst
|
||||
api/pagination_count.rst
|
||||
api/resource_embedding.rst
|
||||
api/resource_representation.rst
|
||||
api/media_type_handlers.rst
|
||||
api/aggregate_functions.rst
|
||||
api/openapi.rst
|
||||
api/preferences.rst
|
||||
api/*
|
||||
|
||||
.. raw:: html
|
||||
@@ -26,22 +30,22 @@ PostgREST exposes three database objects of a schema as resources: tables, views
|
||||
|
||||
const redirects = {
|
||||
// Tables and Views
|
||||
'#horizontal-filtering-rows': 'api/tables_views.html#horizontal-filtering-rows',
|
||||
'#horizontal-filtering-rows': 'api/tables_views.html#horizontal-filtering',
|
||||
'#operators': 'api/tables_views.html#operators',
|
||||
'#logical-operators': 'api/tables_views.html#logical-operators',
|
||||
'#pattern-matching': 'api/tables_views.html#pattern-matching',
|
||||
'#full-text-search': 'api/tables_views.html#full-text-search',
|
||||
'#vertical-filtering-columns': 'api/tables_views.html#vertical-filtering-columns',
|
||||
'#vertical-filtering-columns': 'api/tables_views.html#vertical-filtering',
|
||||
'#renaming-columns': 'api/tables_views.html#renaming-columns',
|
||||
'#casting-columns': 'api/tables_views.html#casting-columns',
|
||||
'#json-columns': 'api/tables_views.html#json-columns',
|
||||
'#composite-array-columns': 'api/tables_views.html#composite-array-columns',
|
||||
'#computed-virtual-columns': 'api/computed_fields.html#computed-fields',
|
||||
'#computed-virtual-columns': 'api/computed_fields.html',
|
||||
'#ordering': 'api/tables_views.html#ordering',
|
||||
'#limits-and-pagination': 'api/tables_views.html#limits-and-pagination',
|
||||
'#exact-count': 'api/tables_views.html#exact-count',
|
||||
'#planned-count': 'api/tables_views.html#planned-count',
|
||||
'#estimated-count': 'api/tables_views.html#estimated-count',
|
||||
'#limits-and-pagination': 'api/pagination_count.html',
|
||||
'#exact-count': 'api/pagination_count.html#exact-count',
|
||||
'#planned-count': 'api/pagination_count.html#planned-count',
|
||||
'#estimated-count': 'api/pagination_count.html#estimated-count',
|
||||
'#updates': 'api/tables_views.html#update',
|
||||
'#insertions': 'api/tables_views.html#insert',
|
||||
'#bulk-insert': 'api/tables_views.html#bulk-insert',
|
||||
@@ -51,15 +55,15 @@ PostgREST exposes three database objects of a schema as resources: tables, views
|
||||
'#put': 'api/tables_views.html#put',
|
||||
'#deletions': 'api/tables_views.html#delete',
|
||||
'#limited-updates-deletions': 'api/tables_views.html#limited-update-delete',
|
||||
// Stored procedures
|
||||
'#stored-procedures': 'api/stored_procedures.html#stored-procedures',
|
||||
'#calling-functions-with-a-single-json-parameter': 'api/stored_procedures.html#functions-with-a-single-json-parameter',
|
||||
'#calling-functions-with-a-single-unnamed-parameter': 'api/stored_procedures.html#functions-with-a-single-unnamed-parameter',
|
||||
'#calling-functions-with-array-parameters': 'api/stored_procedures.html#functions-with-array-parameters',
|
||||
'#calling-variadic-functions': 'api/stored_procedures.html#variadic-functions',
|
||||
'#scalar-functions': 'api/stored_procedures.html#scalar-functions',
|
||||
'#function-filters': 'api/stored_procedures.html#table-valued-functions',
|
||||
'#overloaded-functions': 'api/stored_procedures.html#overloaded-functions',
|
||||
// Functions
|
||||
'#stored-procedures': 'api/functions.html',
|
||||
'#calling-functions-with-a-single-json-parameter': 'api/functions.html#functions-with-a-single-json-parameter',
|
||||
'#calling-functions-with-a-single-unnamed-parameter': 'api/functions.html#functions-with-a-single-unnamed-parameter',
|
||||
'#calling-functions-with-array-parameters': 'api/functions.html#functions-with-array-parameters',
|
||||
'#calling-variadic-functions': 'api/functions.html#variadic-functions',
|
||||
'#scalar-functions': 'api/functions.html#scalar-functions',
|
||||
'#function-filters': 'api/functions.html#table-valued-functions',
|
||||
'#overloaded-functions': 'api/functions.html#overloaded-functions',
|
||||
// Schemas
|
||||
'#switching-schemas': 'api/schemas.html',
|
||||
// Resource Embedding
|
||||
@@ -72,21 +76,21 @@ PostgREST exposes three database objects of a schema as resources: tables, views
|
||||
'#nested-embedding': 'api/resource_embedding.html#nested-embedding',
|
||||
'#embedded-filters': 'api/resource_embedding.html#embedded-filters',
|
||||
'#embedding-with-top-level-filtering': 'api/resource_embedding.html#top-level-filtering',
|
||||
'#embedding-partitioned-tables': 'api/resource_embedding.html#embedding-partitioned-tables',
|
||||
'#embedding-views': 'api/resource_embedding.html#embedding-views',
|
||||
'#embedding-chains-of-views': 'api/resource_embedding.html#embedding-chains-of-views',
|
||||
'#embedding-on-stored-procedures': 'api/resource_embedding.html#embedding-on-stored-procedures',
|
||||
'#embedding-after-insertions-updates-deletions': 'api/resource_embedding.html#embedding-after-insertions-updates-deletions',
|
||||
'#embedding-disambiguation': 'api/resource_embedding.html#embedding-disambiguation',
|
||||
'#target-disambiguation': 'api/resource_embedding.html#target-disambiguation',
|
||||
'#hint-disambiguation': 'api/resource_embedding.html#hint-disambiguation',
|
||||
'#embedding-partitioned-tables': 'api/resource_embedding.html#foreign-key-joins-on-partitioned-tables',
|
||||
'#embedding-views': 'api/resource_embedding.html#foreign-key-joins-on-views',
|
||||
'#embedding-chains-of-views': 'api/resource_embedding.html#foreign-key-joins-on-chains-of-views',
|
||||
'#embedding-on-stored-procedures': 'api/resource_embedding.html#foreign-key-joins-on-table-valued-functions',
|
||||
'#embedding-after-insertions-updates-deletions': 'api/resource_embedding.html#foreign-key-joins-on-writes',
|
||||
'#embedding-disambiguation': 'api/resource_embedding.html#foreign-key-joins-on-multiple-foreign-key-relationships',
|
||||
'#target-disambiguation': 'api/resource_embedding.html#foreign-key-joins-on-multiple-foreign-key-relationships',
|
||||
'#hint-disambiguation': 'api/resource_embedding.html#foreign-key-joins-on-multiple-foreign-key-relationships',
|
||||
"#embedding-through-join-tables": "api/resource_embedding.html#many-to-many-relationships",
|
||||
// OpenAPI
|
||||
'#openapi-support': 'api/openapi.html',
|
||||
// Resource Representation
|
||||
'#response-format': 'api/resource_representation.html#response-format',
|
||||
'#singular-or-plural': 'api/resource_representation.html#singular-or-plural',
|
||||
'#response-formats-for-scalar-responses': 'api/resource_representation.html#scalar-function-response-format',
|
||||
'#response-formats-for-scalar-responses': 'api/functions.html#scalar-functions',
|
||||
// CORS
|
||||
'#cors': 'api/cors.html',
|
||||
// OPTIONS
|
||||
@@ -100,14 +104,14 @@ PostgREST exposes three database objects of a schema as resources: tables, views
|
||||
'#immutable-and-stable-functions': 'transactions.html#access-mode',
|
||||
'#http-context': 'transactions.html#transaction-scoped-settings',
|
||||
'#accessing-request-headers-cookies-and-jwt-claims': 'transactions.html#request-headers-cookies-and-jwt-claims',
|
||||
'#legacy-guc-variable-names': 'transactions.html#legacy-settings',
|
||||
'#legacy-guc-variable-names': 'transactions.html#transaction-scoped-settings',
|
||||
'#accessing-request-path-and-method': 'transactions.html#request-path-and-method',
|
||||
'#setting-response-headers': 'transactions.html#response-headers',
|
||||
'#setting-headers-via-pre-request': 'transactions.html#setting-headers-via-pre-request',
|
||||
'#setting-response-status-code': 'transactions.html#response-status-code',
|
||||
'#raise-errors-with-http-status-codes': 'transactions.html#raise-errors-with-http-status-codes',
|
||||
'#raise-errors-with-http-status-codes': 'errors.html#raise-errors-with-http-status-codes',
|
||||
// Admin
|
||||
'#execution-plan': 'admin.html#execution-plan',
|
||||
'#execution-plan': 'observability.html#execution-plan',
|
||||
// Deprecated
|
||||
'#bulk-call': '../releases/v11.0.1.html#breaking-changes',
|
||||
};
|
||||
|
||||
@@ -0,0 +1,288 @@
|
||||
.. _aggregate_functions:
|
||||
|
||||
Aggregate Functions
|
||||
###################
|
||||
|
||||
Aggregate functions allow you to summarize data by performing calculations across groups of rows. For instance, if you have an ``orders`` table that has an ``amount`` column, you could use an aggregate function to get the sum of the ``amount`` column, either for all rows, or for each group of rows that share specific values, for instance all rows that share the same ``order_date``.
|
||||
|
||||
.. note::
|
||||
Aggregate functions are *disabled* by default in PostgREST, as without appropriate safeguards, aggregate functions can create performance problems. See :ref:`db-aggregates-enabled` for further details.
|
||||
|
||||
PostgREST supports the following aggregate functions: ``avg()``, ``count()``, ``max()``, ``min()``, and ``sum()``. Please refer to the `section on aggregate functions in the PostgreSQL documentation <https://www.postgresql.org/docs/current/functions-aggregate.html>`_ for a detailed explanation of these functions.
|
||||
|
||||
To use an aggregate function, you append the function to a value in the ``select`` parameter, like so:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3000/orders?select=amount.sum()"
|
||||
|
||||
With the above query, PostgREST will return a single row with a single column named ``sum`` that contains the sum of all the values in the ``amount`` column:
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
[
|
||||
{
|
||||
"sum": 1234.56
|
||||
}
|
||||
]
|
||||
|
||||
You can use multiple aggregate functions by just adding more columns with aggregate functions to the ``select`` parameter.
|
||||
|
||||
To group by other columns, you simply add those columns to the ``select`` parameter. For instance:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3000/orders?select=amount.sum(),amount.avg(),order_date"
|
||||
|
||||
This will return a row for each unique value in the ``order_date`` column, with the sum and average of the ``amount`` column for all rows that share the same ``order_date``:
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
[
|
||||
{
|
||||
"sum": 1234.56,
|
||||
"avg": 123.45,
|
||||
"order_date": "2023-01-01"
|
||||
},
|
||||
{
|
||||
"sum": 2345.67,
|
||||
"avg": 234.56,
|
||||
"order_date": "2023-01-02"
|
||||
}
|
||||
]
|
||||
|
||||
.. note::
|
||||
Aggregate functions work alongside other PostgREST features, like :ref:`h_filter`, :ref:`json_columns`, and :ref:`ordering`. Please note at this time aggregate functions are not compatible with :ref:`domain_reps`. Additionally, PostgreSQL's ``HAVING`` clause and ordering by aggregated columns are not yet supported.
|
||||
|
||||
The Case of ``count()``
|
||||
===========================
|
||||
|
||||
.. note::
|
||||
Before the addition of aggregate functions, it was possible to count by adding ``count`` (without parentheses) to the ``select`` parameter. While this is still supported, it may be deprecated in the future, and thus use of this legacy feature is **not recommended.** Please use ``count()`` (with parentheses) instead.
|
||||
|
||||
|
||||
``count()`` is treated specially, as it can be used without an associated column. Take for example the following query:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3000/orders?select=count(),order_date"
|
||||
|
||||
This would return a row for each unique value in the ``order_date`` column, with the count of all rows that share the same ``order_date``:
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
[
|
||||
{
|
||||
"count": 4,
|
||||
"order_date": "2023-01-01"
|
||||
},
|
||||
{
|
||||
"count": 2,
|
||||
"order_date": "2023-01-02"
|
||||
}
|
||||
]
|
||||
|
||||
When ``count()`` is used with an associated column, its behavior is slightly different: It will return the count of all values that are not ``NULL``. This is due to how PostgreSQL itself implements the ``count()`` function.
|
||||
|
||||
Renaming and Casting
|
||||
====================
|
||||
|
||||
Renaming Aggregates
|
||||
-------------------
|
||||
|
||||
Just like with other columns, you can rename aggregated columns too. See :ref:`renaming_columns` for details.
|
||||
|
||||
Renaming columns is especially helpful in the context of aggregate functions, as by default a column with an aggregate function applied will take on the name of the applied aggregate function. You may want to provide a more semantically meaningful name or prevent collisions when using multiple aggregate functions of the same type.
|
||||
|
||||
Casting Aggregates
|
||||
------------------
|
||||
|
||||
When applying an aggregate function to a column, you are able to cast both the value of the input to the aggregate function *and* the value of the output from the aggregate function. In both cases, the syntax works as described in :ref:`casting_columns`, with the only difference being the placement of the cast.
|
||||
|
||||
Casting the Value of the Input
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
For instance, imagine that the ``orders`` table has a JSON column, ``order_details``, and this column contains a JSON object that has a key, ``tax_amount``. Let's say you want to get the sum of the tax amount for every order. You can use the ``->`` or ``->>`` operators to extract the value with this key (see :ref:`json_columns`), but these operators will return values of the types JSON and ``text`` respectively, and neither of these types can be used with ``sum()``.
|
||||
|
||||
Therefore, you will need to first cast the input value to a type that is compatible with ``sum()`` (e.g. ``numeric``). Casting the input value is done in exactly the same way as casting any other value:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3000/orders?select=order_details->tax_amount::numeric.sum()"
|
||||
|
||||
With this, you will receive the sum of the casted ``tax_amount`` value:
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
[
|
||||
{
|
||||
"sum": 1234.56
|
||||
}
|
||||
]
|
||||
|
||||
Casting the Value of the Output
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Now let's return to an example involving the ``amount`` column of the ``orders`` table. Imagine that we want to get the rounded average of the ``amount`` column. One way to do this is to use the ``avg()`` aggregate function and then to cast the output value of the function to ``int``. To cast the value of the output of the function, we simply place the cast *after* the aggregate function:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3000/orders?select=amount.avg()::int"
|
||||
|
||||
You will then receive the rounded average as the result:
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
[
|
||||
{
|
||||
"avg": 201
|
||||
}
|
||||
]
|
||||
|
||||
Of course, you can use both input and output casts at the same time, if you so desire.
|
||||
|
||||
|
||||
Using Aggregate Functions with Resource Embedding
|
||||
=================================================
|
||||
|
||||
Aggregate functions can be used in conjunction with :ref:`resource_embedding`. You can use embedded resources as grouping columns, use aggregate functions within the context of an embedded resource, or use columns from a spreaded resource as grouping columns or as inputs to aggregate functions.
|
||||
|
||||
Using Embedded Resources as Grouping Columns
|
||||
--------------------------------------------
|
||||
|
||||
Using an embedded resource as a grouping column allows you to use data from an association to group the results of an aggregation.
|
||||
|
||||
For example, imagine that the ``orders`` table from the examples above is related to a ``customers`` table. If you want to get the sum of the ``amount`` column grouped by the ``name`` column from the ``customers`` table, you can include the customer name, using the standard :ref:`resource_embedding` syntax, and perform a sum on the ``amount`` column.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3000/orders?select=amount.sum(),customers(name)"
|
||||
|
||||
You will then get the summed amount, along with the embedded customer resource:
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
[
|
||||
{
|
||||
"sum": 100,
|
||||
"customers": {
|
||||
"name": "Customer A"
|
||||
}
|
||||
},
|
||||
{
|
||||
"sum": 200,
|
||||
"customers": {
|
||||
"name": "Customer B"
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
.. note::
|
||||
The previous example uses a has-one association to demonstrate this functionality, but you may also use has-many associations as grouping columns, although there are few obvious use cases for this.
|
||||
|
||||
Using Aggregate Functions Within the Context of an Embedded Resource
|
||||
--------------------------------------------------------------------
|
||||
|
||||
When embedding a resource, you can apply aggregate functions to columns from the associated resource to perform aggregations within the context of an embedded resource.
|
||||
|
||||
Continuing with the example relationship between ``orders`` and ``customers`` from the previous section, imagine that you want to fetch the ``name``, ``city``, and ``state`` for each customer, along with the sum of amount of the customer's orders, grouped by the order date. This can be done in the following way:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3000/customers?select=name,city,state,orders(amount.sum(),order_date)"
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
[
|
||||
{
|
||||
"name": "Customer A",
|
||||
"city": "New York",
|
||||
"state": "NY",
|
||||
"orders": [
|
||||
{
|
||||
"sum": 215.22,
|
||||
"order_date": "2023-09-01"
|
||||
},
|
||||
{
|
||||
"sum": 905.73,
|
||||
"order_date": "2023-09-02"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Customer B",
|
||||
"city": "Los Angeles",
|
||||
"state": "CA",
|
||||
"orders": [
|
||||
{
|
||||
"sum": 329.71,
|
||||
"order_date": "2023-09-01"
|
||||
},
|
||||
{
|
||||
"sum": 425.87,
|
||||
"order_date": "2023-09-03"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
In this example, the ``amount`` column is summed and grouped by the ``order_date`` *within* the context of the embedded resource. That is, the ``name``, ``city``, and ``state`` from the ``customers`` table have no bearing on the aggregation performed in the context of the ``orders`` association; instead, each aggregation can be seen as being performed independently on just the orders belonging to a particular customer, using only the data from the embedded resource for both grouping and aggregation.
|
||||
|
||||
Using Columns from a Spreaded Resource
|
||||
--------------------------------------
|
||||
|
||||
When you :ref:`spread an embedded resource <spread_embed>`, the columns from the spreaded resource are treated as if they were columns of the top-level resource, both when using them as grouping columns and when applying aggregate functions to them.
|
||||
|
||||
Grouping with Columns from a Spreaded Resource
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
For instance, assume you want to sum the ``amount`` column from the ``orders`` table, using the ``city`` and ``state`` columns from the ``customers`` table as grouping columns. To achieve this, you may select these two columns from the ``customers`` table and spread them; they will then be used as grouping columns:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3000/orders?select=amount.sum(),...customers(city,state)
|
||||
|
||||
The result will be the same as if ``city`` and ``state`` were columns from the ``orders`` table:
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
[
|
||||
{
|
||||
"sum": 2000.29,
|
||||
"city": "New York",
|
||||
"state": "NY"
|
||||
},
|
||||
{
|
||||
"sum": 9241.21,
|
||||
"city": "Los Angeles",
|
||||
"state": "CA"
|
||||
}
|
||||
]
|
||||
|
||||
Aggregate Functions with Columns from a Spreaded Resource
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Now imagine that the ``customers`` table has a ``joined_date`` column that represents the date that the customer joined. You want to get both the most recent and the oldest ``joined_date`` for customers that placed an order on every distinct order date. This can be expressed as follows:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3000/orders?select=order_date,...customers(joined_date.max(),joined_date.min())
|
||||
|
||||
As columns from a spreaded resource are treated as if they were columns from the top-level resource, the ``max()`` and ``min()`` are applied *within* the context of the top-level, rather than within the context of the embedded resource, as in the previous section.
|
||||
|
||||
The result will be the same as if the aggregations were applied to columns from the top-level:
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
[
|
||||
{
|
||||
"order_date": "2023-11-01",
|
||||
"max": "2023-10-15",
|
||||
"min": "2013-10-01"
|
||||
},
|
||||
{
|
||||
"order_date": "2023-11-02",
|
||||
"max": "2023-10-30",
|
||||
"min": "2016-02-11"
|
||||
}
|
||||
]
|
||||
@@ -30,15 +30,9 @@ Horizontal Filtering on Computed Fields
|
||||
CREATE INDEX people_full_name_idx ON people
|
||||
USING GIN (to_tsvector('english', full_name(people)));
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
GET /people?full_name=fts.Beckett HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/people?full_name=fts.Beckett"
|
||||
curl "http://localhost:3000/people?full_name=fts.Beckett"
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
@@ -51,15 +45,9 @@ Vertical Filtering on Computed Fields
|
||||
|
||||
Computed fields won't appear on the response by default but you can use :ref:`v_filter` to include them:
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
GET /people?select=full_name,job HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/people?select=full_name,job"
|
||||
curl "http://localhost:3000/people?select=full_name,job"
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
@@ -72,19 +60,13 @@ Ordering on Computed Fields
|
||||
|
||||
:ref:`ordering` on computed fields is also possible:
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
GET /people?order=full_name.desc HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/people?order=full_name.desc"
|
||||
curl "http://localhost:3000/people?order=full_name.desc"
|
||||
|
||||
.. important::
|
||||
|
||||
Computed columns must be created in the :ref:`exposed schema <db-schemas>` or in a schema in the :ref:`extra search path <db-extra-search-path>` to be used in this way. When placing the computed column in the :ref:`exposed schema <db-schemas>` you can use an **unnamed** parameter, as in the example above, to prevent it from being exposed as an :ref:`RPC <s_procs>` under ``/rpc``.
|
||||
Computed fields must be created in the :ref:`exposed schema <db-schemas>` or in a schema in the :ref:`extra search path <db-extra-search-path>` to be used in this way. When placing the computed field in the :ref:`exposed schema <db-schemas>` you can use an **unnamed** parameter, as in the example above, to prevent it from being exposed as an :ref:`RPC <functions>` under ``/rpc``.
|
||||
|
||||
.. note::
|
||||
|
||||
|
||||
@@ -1,28 +1,22 @@
|
||||
.. _cors:
|
||||
|
||||
CORS
|
||||
====
|
||||
####
|
||||
|
||||
By default, PostgREST sets highly permissive cross origin resource sharing, that is why it accepts Ajax requests from any domain. This behavior can be configured by using :ref:`server_cors_allowed_origins`.
|
||||
|
||||
PostgREST sets highly permissive cross origin resource sharing, that is why it accepts Ajax requests from any domain.
|
||||
|
||||
It also handles `preflight requests <https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request>`_ done by the browser, which are cached using the returned ``Access-Control-Max-Age: 86400`` header (86400 seconds = 24 hours). This is useful to reduce the latency of the subsequent requests.
|
||||
|
||||
A ``POST`` preflight request would look like this:
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
OPTIONS /items HTTP/1.1
|
||||
Origin: http://example.com
|
||||
Access-Control-Allow-Method: POST
|
||||
Access-Control-Allow-Headers: Content-Type
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl -i "http://localhost:3000/items" \
|
||||
-X OPTIONS \
|
||||
-H "Origin: http://example.com" \
|
||||
-H "Access-Control-Request-Method: POST" \
|
||||
-H "Access-Control-Request-Headers: Content-Type"
|
||||
curl -i "http://localhost:3000/items" \
|
||||
-X OPTIONS \
|
||||
-H "Origin: http://example.com" \
|
||||
-H "Access-Control-Request-Method: POST" \
|
||||
-H "Access-Control-Request-Headers: Content-Type"
|
||||
|
||||
.. code-block:: http
|
||||
|
||||
@@ -32,3 +26,15 @@ A ``POST`` preflight request would look like this:
|
||||
Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS, HEAD
|
||||
Access-Control-Allow-Headers: Authorization, Content-Type, Accept, Accept-Language, Content-Language
|
||||
Access-Control-Max-Age: 86400
|
||||
|
||||
.. _allowed_origins:
|
||||
|
||||
Allowed Origins
|
||||
===============
|
||||
|
||||
With the following config setting, PostgREST will accept CORS requests from domains :code:`http://example.com` and :code:`http://example2.com`.
|
||||
|
||||
|
||||
.. code-block::
|
||||
|
||||
server-cors-allowed-origins="http://example.com, http://example2.com"
|
||||
|
||||
@@ -58,17 +58,10 @@ Then create a CAST to tell PostgREST to convert it automatically whenever a JSON
|
||||
|
||||
With this you can obtain the data in the shortened format.
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
GET /profiles HTTP/1.1
|
||||
Accept: application/json
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/profiles" \
|
||||
-H "Accept: application/json"
|
||||
curl "http://localhost:3000/profiles" \
|
||||
-H "Accept: application/json"
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
@@ -102,17 +95,10 @@ PostgREST considers the URL query string to be, in the most generic sense, ``tex
|
||||
|
||||
Now you can filter as usual.
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
GET /profiles?id=eq.hGxP/ZLOTeeNEY4pkp9OxA== HTTP/1.1
|
||||
Accept: application/json
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/profiles?id=eq.ZLOTeeNEY4pkp9OxA==" \
|
||||
-H "Accept: application/json"
|
||||
curl "http://localhost:3000/profiles?id=eq.ZLOTeeNEY4pkp9OxA==" \
|
||||
-H "Accept: application/json"
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
@@ -139,26 +125,16 @@ To accept the shortened format in a JSON request body, for example when creating
|
||||
|
||||
Now we can :ref:`insert` (or :ref:`update`) as usual.
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
curl "http://localhost:3000/profiles" \
|
||||
-H "Prefer: return=representation" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d @- <<JSON
|
||||
|
||||
POST /profiles HTTP/1.1
|
||||
Content-Type: application/json
|
||||
Prefer: return=representation
|
||||
{"id":"zH7HbFJUTfy/GZpwuirpuQ==","name":"Jane Doe"}
|
||||
|
||||
{"id":"zH7HbFJUTfy/GZpwuirpuQ==","name":"Jane Doe"}
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/profiles" \
|
||||
-H "Prefer: return=representation" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d @- <<JSON
|
||||
|
||||
{"id":"zH7HbFJUTfy/GZpwuirpuQ==","name":"Jane Doe"}
|
||||
|
||||
JSON
|
||||
JSON
|
||||
|
||||
The response:
|
||||
|
||||
|
||||
@@ -0,0 +1,344 @@
|
||||
.. _functions:
|
||||
|
||||
Functions as RPC
|
||||
================
|
||||
|
||||
*"A single resource can be the equivalent of a database function, with the power to abstract state changes over any number of storage items"* -- `Roy T. Fielding <https://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven#comment-743>`_
|
||||
|
||||
Functions can perform any operation allowed by PostgreSQL (read data, modify data, :ref:`raise errors <raise_error>`, and even DDL operations). Every function in the :ref:`exposed schema <schemas>` and accessible by the :ref:`active database role <roles>` is executable under the :code:`/rpc` prefix.
|
||||
|
||||
If they return table types, functions can:
|
||||
|
||||
- Use all the same :ref:`read filters as Tables and Views <read>` (horizontal/vertical filtering, counts, limits, etc.).
|
||||
- Use :ref:`Resource Embedding <function_embed>`, if the returned table type has relationships to other tables.
|
||||
|
||||
.. note::
|
||||
|
||||
Why the ``/rpc`` prefix? PostgreSQL allows a table or view to have the same name as a function. The prefix allows us to avoid routes collisions.
|
||||
|
||||
.. warning::
|
||||
|
||||
`Stored Procedures <https://www.postgresql.org/docs/current/xproc.html>`_ are not supported.
|
||||
|
||||
Calling with POST
|
||||
-----------------
|
||||
|
||||
To supply arguments in an API call, include a JSON object in the request payload. Each key/value of the object will become an argument.
|
||||
|
||||
For instance, assume we have created this function in the database.
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
CREATE FUNCTION add_them(a integer, b integer)
|
||||
RETURNS integer AS $$
|
||||
SELECT a + b;
|
||||
$$ LANGUAGE SQL IMMUTABLE;
|
||||
|
||||
.. important::
|
||||
|
||||
Whenever you create or change a function you must refresh PostgREST's schema cache. See the section :ref:`schema_reloading`.
|
||||
|
||||
The client can call it by posting an object like
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3000/rpc/add_them" \
|
||||
-X POST -H "Content-Type: application/json" \
|
||||
-d '{ "a": 1, "b": 2 }'
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
3
|
||||
|
||||
.. note::
|
||||
|
||||
PostgreSQL converts identifier names to lowercase unless you quote them like:
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
CREATE FUNCTION "someFunc"("someParam" text) ...
|
||||
|
||||
Calling with GET
|
||||
----------------
|
||||
|
||||
If the function doesn't modify the database, it will also run under the GET method (see :ref:`access_mode`).
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3000/rpc/add_them?a=1&b=2"
|
||||
|
||||
The function parameter names match the JSON object keys in the POST case, for the GET case they match the query parameters ``?a=1&b=2``.
|
||||
|
||||
.. _function_single_json:
|
||||
|
||||
Functions with a single unnamed JSON parameter
|
||||
----------------------------------------------
|
||||
|
||||
If you want the JSON request body to be sent as a single argument, you can create a function with a single unnamed ``json`` or ``jsonb`` parameter.
|
||||
For this the ``Content-Type: application/json`` header must be included in the request.
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
CREATE FUNCTION mult_them(json) RETURNS int AS $$
|
||||
SELECT ($1->>'x')::int * ($1->>'y')::int
|
||||
$$ LANGUAGE SQL;
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3000/rpc/mult_them" \
|
||||
-X POST -H "Content-Type: application/json" \
|
||||
-d '{ "x": 4, "y": 2 }'
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
8
|
||||
|
||||
.. note::
|
||||
|
||||
If an overloaded function has a single ``json`` or ``jsonb`` unnamed parameter, PostgREST will call this function as a fallback provided that no other overloaded function is found with the parameters sent in the POST request.
|
||||
|
||||
.. warning::
|
||||
|
||||
Sending the JSON request body as a single argument is also possible with :ref:`Prefer: params=single-object <prefer_params>` but this method is **deprecated**.
|
||||
|
||||
.. _function_single_unnamed:
|
||||
|
||||
Functions with a single unnamed parameter
|
||||
-----------------------------------------
|
||||
|
||||
You can make a POST request to a function with a single unnamed parameter to send raw ``bytea``, ``text`` or ``xml`` data.
|
||||
|
||||
To send raw XML, the parameter type must be ``xml`` and the header ``Content-Type: text/xml`` must be included in the request.
|
||||
|
||||
To send raw binary, the parameter type must be ``bytea`` and the header ``Content-Type: application/octet-stream`` must be included in the request.
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
CREATE TABLE files(blob bytea);
|
||||
|
||||
CREATE FUNCTION upload_binary(bytea) RETURNS void AS $$
|
||||
INSERT INTO files(blob) VALUES ($1);
|
||||
$$ LANGUAGE SQL;
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3000/rpc/upload_binary" \
|
||||
-X POST -H "Content-Type: application/octet-stream" \
|
||||
--data-binary "@file_name.ext"
|
||||
|
||||
.. code-block:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
|
||||
[ ... ]
|
||||
|
||||
To send raw text, the parameter type must be ``text`` and the header ``Content-Type: text/plain`` must be included in the request.
|
||||
|
||||
.. _functions_array:
|
||||
|
||||
Functions with array parameters
|
||||
-------------------------------
|
||||
|
||||
You can call a function that takes an array parameter:
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
create function plus_one(arr int[]) returns int[] as $$
|
||||
SELECT array_agg(n + 1) FROM unnest($1) AS n;
|
||||
$$ language sql;
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3000/rpc/plus_one" \
|
||||
-X POST -H "Content-Type: application/json" \
|
||||
-d '{"arr": [1,2,3,4]}'
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
[2,3,4,5]
|
||||
|
||||
For calling the function with GET, you can pass the array as an `array literal <https://www.postgresql.org/docs/current/arrays.html#ARRAYS-INPUT>`_,
|
||||
as in ``{1,2,3,4}``. Note that the curly brackets have to be urlencoded(``{`` is ``%7B`` and ``}`` is ``%7D``).
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3000/rpc/plus_one?arr=%7B1,2,3,4%7D'"
|
||||
|
||||
.. note::
|
||||
|
||||
For versions prior to PostgreSQL 10, to pass a PostgreSQL native array on a POST payload, you need to quote it and use an array literal:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3000/rpc/plus_one" \
|
||||
-X POST -H "Content-Type: application/json" \
|
||||
-d '{ "arr": "{1,2,3,4}" }'
|
||||
|
||||
In these versions we recommend using function parameters of type JSON to accept arrays from the client.
|
||||
|
||||
.. _functions_variadic:
|
||||
|
||||
Variadic functions
|
||||
------------------
|
||||
|
||||
You can call a variadic function by passing a JSON array in a POST request:
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
create function plus_one(variadic v int[]) returns int[] as $$
|
||||
SELECT array_agg(n + 1) FROM unnest($1) AS n;
|
||||
$$ language sql;
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3000/rpc/plus_one" \
|
||||
-X POST -H "Content-Type: application/json" \
|
||||
-d '{"v": [1,2,3,4]}'
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
[2,3,4,5]
|
||||
|
||||
In a GET request, you can repeat the same parameter name:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3000/rpc/plus_one?v=1&v=2&v=3&v=4"
|
||||
|
||||
Repeating also works in POST requests with ``Content-Type: application/x-www-form-urlencoded``:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3000/rpc/plus_one" \
|
||||
-X POST -H "Content-Type: application/x-www-form-urlencoded" \
|
||||
-d 'v=1&v=2&v=3&v=4'
|
||||
|
||||
.. _table_functions:
|
||||
|
||||
Table-Valued Functions
|
||||
----------------------
|
||||
|
||||
A function that returns a table type can be filtered using the same filters as :ref:`tables and views <tables_views>`. They can also use :ref:`Resource Embedding <function_embed>`.
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
CREATE FUNCTION best_films_2017() RETURNS SETOF films ..
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3000/rpc/best_films_2017?select=title,director:directors(*)"
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3000/rpc/best_films_2017?rating=gt.8&order=title.desc"
|
||||
|
||||
.. _function_inlining:
|
||||
|
||||
Function Inlining
|
||||
~~~~~~~~~~~~~~~~~
|
||||
|
||||
A function that follows the `rules for inlining <https://wiki.postgresql.org/wiki/Inlining_of_SQL_functions#Inlining_conditions_for_table_functions>`_ will also inline :ref:`filters <h_filter>`, :ref:`order <ordering>` and :ref:`limits <limits>`.
|
||||
|
||||
For example, for the following function:
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
create function getallprojects() returns setof projects
|
||||
language sql stable
|
||||
as $$
|
||||
select * from projects;
|
||||
$$;
|
||||
|
||||
Let's get its :ref:`explain_plan` when calling it with filters applied:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3000/rpc/getallprojects?id=eq.1" \
|
||||
-H "Accept: application/vnd.pgrst.plan"
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
Aggregate (cost=8.18..8.20 rows=1 width=112)
|
||||
-> Index Scan using projects_pkey on projects (cost=0.15..8.17 rows=1 width=40)
|
||||
Index Cond: (id = 1)
|
||||
|
||||
Notice there's no "Function Scan" node in the plan, which tells us it has been inlined.
|
||||
|
||||
.. _scalar_functions:
|
||||
|
||||
Scalar functions
|
||||
----------------
|
||||
|
||||
PostgREST will detect if the function is scalar or table-valued and will shape the response format accordingly:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3000/rpc/add_them?a=1&b=2"
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
3
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3000/rpc/best_films_2017"
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
[
|
||||
{ "title": "Okja", "rating": 7.4},
|
||||
{ "title": "Call me by your name", "rating": 8},
|
||||
{ "title": "Blade Runner 2049", "rating": 8.1}
|
||||
]
|
||||
|
||||
To manually choose a return format such as binary, see :ref:`custom_media`.
|
||||
|
||||
.. _untyped_functions:
|
||||
|
||||
Untyped functions
|
||||
-----------------
|
||||
|
||||
Functions that return ``record`` or ``SETOF record`` are supported:
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
create function projects_setof_record() returns setof record as $$
|
||||
select * from projects;
|
||||
$$ language sql;
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3000/rpc/projects_setof_record"
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
[{"id":1,"name":"Windows 7","client_id":1},
|
||||
{"id":2,"name":"Windows 10","client_id":1},
|
||||
{"id":3,"name":"IOS","client_id":2}]
|
||||
|
||||
However note that they will fail when trying to use :ref:`v_filter` and :ref:`h_filter` on them.
|
||||
|
||||
So while they can be used for quick tests, it's recommended to always choose a strict return type for the function.
|
||||
|
||||
Overloaded functions
|
||||
--------------------
|
||||
|
||||
You can call overloaded functions with different number of arguments.
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
CREATE FUNCTION rental_duration(customer_id integer) ..
|
||||
|
||||
CREATE FUNCTION rental_duration(customer_id integer, from_date date) ..
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3000/rpc/rental_duration?customer_id=232"
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3000/rpc/rental_duration?customer_id=232&from_date=2018-07-01"
|
||||
|
||||
.. important::
|
||||
|
||||
Overloaded functions with the same argument names but different types are not supported.
|
||||
@@ -0,0 +1,318 @@
|
||||
.. _custom_media:
|
||||
|
||||
Media Type Handlers
|
||||
###################
|
||||
|
||||
Media Type Handlers allow PostgREST to deliver custom media types. These handlers extend the :ref:`builtin ones <builtin_media>` and can also override them.
|
||||
|
||||
Media types are expressed as type aliases using `domains <https://www.postgresql.org/docs/current/sql-createdomain.html>`_ and their name must comply to `RFC 6838 requirements <https://datatracker.ietf.org/doc/html/rfc6838#section-4.2>`_.
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
CREATE DOMAIN "application/json" AS json;
|
||||
|
||||
Using these domains, :ref:`functions <functions>` can become handlers and `user-defined aggregates <https://www.postgresql.org/docs/current/xaggr.html>`_ can serve as handlers for :ref:`tables_views` and :ref:`table_functions`.
|
||||
|
||||
.. important::
|
||||
|
||||
- PostgREST vendor media types (``application/vnd.pgrst.plan``, ``application/vnd.pgrst.object`` and ``application/vnd.pgrst.array``) cannot be overriden.
|
||||
- Long media types like ``application/vnd.openxmlformats-officedocument.wordprocessingml.document`` cannot be expressed as domains since they surpass `PostgreSQL identifier length <https://www.postgresql.org/docs/current/limits.html#LIMITS-TABLE>`_.
|
||||
For these you can use the :ref:`any_handler`.
|
||||
|
||||
Handler Function
|
||||
================
|
||||
|
||||
As an example, let's obtain the `TWKB <https://postgis.net/docs/ST_AsTWKB.html>`_ compressed binary format for a PostGIS geometry.
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
create extension postgis;
|
||||
|
||||
create table lines (
|
||||
id int primary key
|
||||
, name text
|
||||
, geom geometry(LINESTRING, 4326)
|
||||
);
|
||||
|
||||
insert into lines values (1, 'line-1', 'LINESTRING(1 1,5 5)'::geometry), (2, 'line-2', 'LINESTRING(2 2,6 6)'::geometry);
|
||||
|
||||
For this you can create a vendor media type.
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
create domain "application/vnd.twkb" as bytea;
|
||||
|
||||
And use it as a return type on a function, to make it a handler.
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
create or replace function get_line (id int)
|
||||
returns "application/vnd.twkb" as $$
|
||||
select st_astwkb(geom) from lines where id = get_line.id;
|
||||
$$ language sql;
|
||||
|
||||
.. note::
|
||||
|
||||
For PostgreSQL <= 12, you'll need a cast on the function body :code:`st_astwkb(geom)::"application/vnd.twkb"`.
|
||||
|
||||
Now you can request the ``TWKB`` output like so:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl 'localhost:3000/rpc/get_line?id=1' -i \
|
||||
-H "Accept: application/vnd.twkb"
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/vnd.twkb
|
||||
|
||||
# binary output
|
||||
|
||||
Note that PostgREST will automatically set the ``Content-Type`` to ``application/vnd.twkb``.
|
||||
|
||||
Handlers for Tables/Views
|
||||
=========================
|
||||
|
||||
To benefit from a compressed format like ``TWKB``, it makes more sense to obtain many rows instead of one. Let's allow that by adding a handler for the table.
|
||||
|
||||
User-defined aggregates can be turned into handlers by using domain media types as the return type of their transition or final functions.
|
||||
|
||||
Let's create a transition function for this example.
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
create or replace function twkb_handler_transition (state bytea, next lines)
|
||||
returns "application/vnd.twkb" as $$
|
||||
select state || st_astwkb(next.geom);
|
||||
$$ language sql;
|
||||
|
||||
Now we'll use it on a new aggregate defined for the ``lines`` table.
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
create or replace aggregate twkb_agg (lines) (
|
||||
initcond = ''
|
||||
, stype = "application/vnd.twkb"
|
||||
, sfunc = twkb_handler_transition
|
||||
);
|
||||
|
||||
.. note::
|
||||
|
||||
You can test see this aggregate working with:
|
||||
|
||||
.. code-block:: psql
|
||||
|
||||
SELECT twkb_agg(l) from lines l;
|
||||
|
||||
twkb_agg
|
||||
---------------------------------------------------------------
|
||||
\xa20002c09a0cc09a0c80ea3080ea30a2000280b51880b51880ea3080ea30
|
||||
(1 row)
|
||||
|
||||
Now you can request the table endpoint with the ``twkb`` media type:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl 'localhost:3000/lines' -i \
|
||||
-H "Accept: application/vnd.twkb"
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/vnd.twkb
|
||||
|
||||
# binary output
|
||||
|
||||
If you have a table-valued function returning the same table type, the handler can also act upon on it.
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
create or replace function get_lines ()
|
||||
returns setof lines as $$
|
||||
select * from lines;
|
||||
$$ language sql;
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl 'localhost:3000/get_lines' -i \
|
||||
-H "Accept: application/vnd.twkb"
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/vnd.twkb
|
||||
|
||||
# binary output
|
||||
|
||||
Overriding a Builtin Handler
|
||||
============================
|
||||
|
||||
Let's override the existing ``text/csv`` handler for the table to provide a more complex CSV output.
|
||||
It'll include a `Byte order mark (BOM) <https://en.wikipedia.org/wiki/Byte_order_mark>`_ plus a ``Content-Disposition`` header to set a name for the downloaded file.
|
||||
|
||||
Create a domain for the standard ``text/csv`` media type.
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
create domain "text/csv" as text;
|
||||
|
||||
And a transition function that returns the domain.
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
create or replace function bom_csv_trans (state text, next lines)
|
||||
returns "text/csv" as $$
|
||||
select state || next.id::text || ',' || next.name || ',' || next.geom::text || E'\n';
|
||||
$$ language sql;
|
||||
|
||||
This time we'll add a final function. This will add the CSV header, the BOM and the ``Content-Disposition`` header.
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
create or replace function bom_csv_final (data "text/csv")
|
||||
returns "text/csv" as $$
|
||||
-- set the Content-Disposition header
|
||||
select set_config('response.headers', '[{"Content-Disposition": "attachment; filename=\"lines.csv\""}]', true);
|
||||
select
|
||||
-- EFBBBF is the BOM in UTF8 https://en.wikipedia.org/wiki/Byte_order_mark#UTF-8
|
||||
convert_from (decode (E'EFBBBF', 'hex'),'UTF8') ||
|
||||
-- the header for the CSV
|
||||
(E'id,name,geom\n' || data);
|
||||
$$ language sql;
|
||||
|
||||
Now use the transition and final function as part of the new aggregate.
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
create or replace aggregate bom_csv_agg (lines) (
|
||||
initcond = ''
|
||||
, stype = "text/csv"
|
||||
, sfunc = bom_csv_trans
|
||||
, finalfunc = bom_csv_final
|
||||
);
|
||||
|
||||
.. note::
|
||||
|
||||
You can test this with:
|
||||
|
||||
.. code-block:: psql
|
||||
|
||||
select bom_csv_agg(l) from lines l;
|
||||
bom_csv_agg
|
||||
-----------------------------------------------------------------------------------------------------
|
||||
id,name,geom +
|
||||
1,line-1,0102000020E610000002000000000000000000F03F000000000000F03F00000000000014400000000000001440+
|
||||
2,line-2,0102000020E6100000020000000000000000000040000000000000004000000000000018400000000000001840+
|
||||
|
||||
(1 row)
|
||||
|
||||
And request it like:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl 'localhost:3000/lines' -i \
|
||||
-H "Accept: text/csv"
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: text/csv
|
||||
Content-Disposition: attachment; filename="lines.csv"
|
||||
|
||||
id,name,geom
|
||||
1,line-1,0102000020E610000002000000000000000000F03F000000000000F03F00000000000014400000000000001440
|
||||
2,line-2,0102000020E6100000020000000000000000000040000000000000004000000000000018400000000000001840
|
||||
|
||||
.. _any_handler:
|
||||
|
||||
The "Any" Handler
|
||||
=================
|
||||
|
||||
For more flexibility, you can also define a catch-all handler by using a domain named ``*/*`` (any media type). This handler obeys the following rules:
|
||||
|
||||
- It responds to all media types and even to requests that don't include an ``Accept`` header.
|
||||
- It sets the ``Content-Type`` header to ``application/octet-stream`` by default, but this can be overridden inside the function with :ref:`guc_resp_hdrs`.
|
||||
- It overrides all other handlers (:ref:`builtin <builtin_media>` or custom), so it's better to do it for an isolated function or view.
|
||||
|
||||
Let's define an any handler for a view that will always respond with ``XML`` output. It will accept ``text/xml``, ``application/xml``, ``*/*`` and reject other media types.
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
create domain "*/*" as bytea;
|
||||
|
||||
-- we'll use an .xml suffix for the view to be clear its output is always XML
|
||||
create view "lines.xml" as
|
||||
select * from lines;
|
||||
|
||||
-- transition function
|
||||
create or replace function lines_xml_trans (state "*/*", next "lines.xml")
|
||||
returns "*/*" as $$
|
||||
select state || xmlelement(name line, xmlattributes(next.id as id, next.name as name), next.geom)::text::bytea || E'\n' ;
|
||||
$$ language sql;
|
||||
|
||||
-- final function
|
||||
create or replace function lines_xml_final (data "*/*")
|
||||
returns "*/*" as $$
|
||||
declare
|
||||
-- get the Accept header
|
||||
req_accept text := current_setting('request.headers', true)::json->>'accept';
|
||||
begin
|
||||
-- when we need to override the default Content-Type (application/octet-stream) set by PostgREST
|
||||
if req_accept = '*/*' then
|
||||
perform set_config('response.headers', json_build_array(json_build_object('Content-Type', 'text/xml'))::text, true);
|
||||
elsif req_accept IN ('application/xml', 'text/xml') then
|
||||
perform set_config('response.headers', json_build_array(json_build_object('Content-Type', req_accept))::text, true);
|
||||
else
|
||||
-- we'll reject other non XML media types, we need to reject manually since */* will command PostgREST to accept all media types
|
||||
raise sqlstate 'PT415' using message = 'Unsupported Media Type';
|
||||
end if;
|
||||
|
||||
return data;
|
||||
end; $$ language plpgsql;
|
||||
|
||||
-- new aggregate
|
||||
create or replace aggregate lines_xml_agg ("lines.xml") (
|
||||
stype = "*/*"
|
||||
, sfunc = lines_xml_trans
|
||||
, finalfunc = lines_xml_final
|
||||
);
|
||||
|
||||
Test it on SQL:
|
||||
|
||||
.. code-block:: psql
|
||||
|
||||
select (encode(lines_xml_agg(x), 'escape'))::xml from "lines.xml" x;
|
||||
encode
|
||||
------------------------------------------------------------------------------------------------------------------------------
|
||||
<line id="1" name="line-1">0102000020E610000002000000000000000000F03F000000000000F03F00000000000014400000000000001440</line>+
|
||||
<line id="2" name="line-2">0102000020E6100000020000000000000000000040000000000000004000000000000018400000000000001840</line>+
|
||||
|
||||
Now we can omit the ``Accept`` header and it will respond with XML.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl 'localhost:3000/lines.xml' -i
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: text/xml
|
||||
|
||||
<line id="1" name="line-1">0102000020E610000002000000000000000000F03F000000000000F03F00000000000014400000000000001440</line>
|
||||
<line id="2" name="line-2">0102000020E6100000020000000000000000000040000000000000004000000000000018400000000000001840</line>
|
||||
|
||||
And it will accept only XML media types.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl 'localhost:3000/lines.xml' -i \
|
||||
-H "Accept: text/xml"
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: text/xml
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl 'localhost:3000/lines.xml' -i \
|
||||
-H "Accept: application/xml"
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: text/xml
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl 'localhost:3000/lines.xml' -i \
|
||||
-H "Accept: unknown/media"
|
||||
|
||||
HTTP/1.1 415 Unsupported Media Type
|
||||
@@ -11,7 +11,7 @@ PostgREST automatically serves a full `OpenAPI <https://www.openapis.org/>`_ des
|
||||
|
||||
For extra customization, the OpenAPI output contains a "description" field for every `SQL comment <https://www.postgresql.org/docs/current/sql-comment.html>`_ on any database object. For instance,
|
||||
|
||||
.. code-block:: sql
|
||||
.. code-block:: postgres
|
||||
|
||||
COMMENT ON SCHEMA mammals IS
|
||||
'A warm-blooded vertebrate animal of a class that is distinguished by the secretion of milk by females for the nourishment of the young';
|
||||
@@ -26,7 +26,7 @@ These unsavory comments will appear in the generated JSON as the fields, ``info.
|
||||
|
||||
Also if you wish to generate a ``summary`` field you can do it by having a multiple line comment, the ``summary`` will be the first line and the ``description`` the lines that follow it:
|
||||
|
||||
.. code-block:: plpgsql
|
||||
.. code-block:: postgres
|
||||
|
||||
COMMENT ON TABLE entities IS
|
||||
$$Entities summary
|
||||
@@ -37,7 +37,7 @@ Also if you wish to generate a ``summary`` field you can do it by having a multi
|
||||
|
||||
Similarly, you can override the API title by commenting the schema.
|
||||
|
||||
.. code-block:: plpgsql
|
||||
.. code-block:: postgres
|
||||
|
||||
COMMENT ON SCHEMA api IS
|
||||
$$FooBar API
|
||||
@@ -81,15 +81,9 @@ You can override the whole default response with a function result. To do this,
|
||||
end
|
||||
$_$ language plpgsql;
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
GET / HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl http://localhost:3000
|
||||
curl http://localhost:3000
|
||||
|
||||
.. code-block:: http
|
||||
|
||||
|
||||
@@ -7,15 +7,9 @@ You can verify which HTTP methods are allowed on endpoints for tables and views
|
||||
|
||||
For a table named ``people``, OPTIONS would show:
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
OPTIONS /people HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/people" -X OPTIONS -i
|
||||
curl "http://localhost:3000/people" -X OPTIONS -i
|
||||
|
||||
.. code-block:: http
|
||||
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
Pagination and Count
|
||||
####################
|
||||
|
||||
Pagination controls the number of rows returned for an :doc:`API resource <../api>` response. Combined with the count, you can traverse all the rows of a response.
|
||||
|
||||
.. _limits:
|
||||
|
||||
Limits and Pagination
|
||||
---------------------
|
||||
|
||||
PostgREST uses HTTP range headers to describe the size of results. Every response contains the current range and, if requested, the total number of results:
|
||||
|
||||
.. code-block:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Range-Unit: items
|
||||
Content-Range: 0-14/*
|
||||
|
||||
Here items zero through fourteen are returned. This information is available in every response and can help you render pagination controls on the client. This is an RFC7233-compliant solution that keeps the response JSON cleaner.
|
||||
|
||||
Query Parameters
|
||||
~~~~~~~~~~~~~~~~
|
||||
|
||||
One way to request limits and offsets is by using query parameters. For example:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3000/people?limit=15&offset=30"
|
||||
|
||||
This method is also useful for embedded resources, which we will cover in another section. The server always responds with range headers even if you use query parameters to limit the query.
|
||||
|
||||
Range Header
|
||||
~~~~~~~~~~~~
|
||||
|
||||
You can use headers to specify the range of rows desired.
|
||||
This request gets the first twenty people:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3000/people" -i \
|
||||
-H "Range-Unit: items" \
|
||||
-H "Range: 0-19"
|
||||
|
||||
Note that the server may respond with fewer if unable to meet your request:
|
||||
|
||||
.. code-block:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Range-Unit: items
|
||||
Content-Range: 0-17/*
|
||||
|
||||
You may also request open-ended ranges for an offset with no limit, e.g. :code:`Range: 10-`.
|
||||
|
||||
.. _prefer_count:
|
||||
|
||||
Counting
|
||||
--------
|
||||
|
||||
In order to obtain the total size of the table (such as when rendering the last page link in a pagination control), you can specify a ``Prefer: count=<value>`` header. The values can be ``exact``, ``planned`` and ``estimated``.
|
||||
|
||||
This also works on views and :ref:`table_functions`.
|
||||
|
||||
|
||||
.. _exact_count:
|
||||
|
||||
Exact Count
|
||||
~~~~~~~~~~~
|
||||
|
||||
To get the exact count, use ``Prefer: count=exact``.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3000/bigtable" -I \
|
||||
-H "Range-Unit: items" \
|
||||
-H "Range: 0-24" \
|
||||
-H "Prefer: count=exact"
|
||||
|
||||
Note that the larger the table the slower this query runs in the database. The server will respond with the selected range and total
|
||||
|
||||
.. code-block:: http
|
||||
|
||||
HTTP/1.1 206 Partial Content
|
||||
Range-Unit: items
|
||||
Content-Range: 0-24/3573458
|
||||
|
||||
.. _planned_count:
|
||||
|
||||
Planned Count
|
||||
~~~~~~~~~~~~~
|
||||
|
||||
To avoid the shortcomings of :ref:`exact count <exact_count>`, PostgREST can leverage PostgreSQL statistics and get a fairly accurate and fast count.
|
||||
To do this, specify the ``Prefer: count=planned`` header.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3000/bigtable?limit=25" -I \
|
||||
-H "Prefer: count=planned"
|
||||
|
||||
.. code-block:: http
|
||||
|
||||
HTTP/1.1 206 Partial Content
|
||||
Content-Range: 0-24/3572000
|
||||
|
||||
Note that the accuracy of this count depends on how up-to-date are the PostgreSQL statistics tables.
|
||||
For example in this case, to increase the accuracy of the count you can do ``ANALYZE bigtable``.
|
||||
See `ANALYZE <https://www.postgresql.org/docs/current/sql-analyze.html>`_ for more details.
|
||||
|
||||
.. _estimated_count:
|
||||
|
||||
Estimated Count
|
||||
~~~~~~~~~~~~~~~
|
||||
|
||||
When you are interested in the count, the relative error is important. If you have a :ref:`planned count <planned_count>` of 1000000 and the exact count is
|
||||
1001000, the error is small enough to be ignored. But with a planned count of 7, an exact count of 28 would be a huge misprediction.
|
||||
|
||||
In general, when having smaller row-counts, the estimated count should be as close to the exact count as possible.
|
||||
|
||||
To help with these cases, PostgREST can get the exact count up until a threshold and get the planned count when
|
||||
that threshold is surpassed. To use this behavior, you can specify the ``Prefer: count=estimated`` header. The **threshold** is
|
||||
defined by :ref:`db-max-rows`.
|
||||
|
||||
Here's an example. Suppose we set ``db-max-rows=1000`` and ``smalltable`` has 321 rows, then we'll get the exact count:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3000/smalltable?limit=25" -I \
|
||||
-H "Prefer: count=estimated"
|
||||
|
||||
.. code-block:: http
|
||||
|
||||
HTTP/1.1 206 Partial Content
|
||||
Content-Range: 0-24/321
|
||||
|
||||
If we make a similar request on ``bigtable``, which has 3573458 rows, we would get the planned count:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3000/bigtable?limit=25" -I \
|
||||
-H "Prefer: count=estimated"
|
||||
|
||||
.. code-block:: http
|
||||
|
||||
HTTP/1.1 206 Partial Content
|
||||
Content-Range: 0-24/3572000
|
||||
@@ -0,0 +1,254 @@
|
||||
.. _preferences:
|
||||
|
||||
Prefer Header
|
||||
#############
|
||||
|
||||
PostgREST honors the Prefer HTTP header specified on `RFC 7240 <https://www.rfc-editor.org/rfc/rfc7240.html>`_. It allows clients to specify required and optional behaviors for their requests.
|
||||
|
||||
The following preferences are supported.
|
||||
|
||||
- ``Prefer: handling``. See :ref:`prefer_handling`.
|
||||
- ``Prefer: timezone``. See :ref:`prefer_timezone`.
|
||||
- ``Prefer: return``. See :ref:`prefer_return`.
|
||||
- ``Prefer: count``. See :ref:`prefer_count`.
|
||||
- ``Prefer: resolution``. See :ref:`prefer_resolution`.
|
||||
- ``Prefer: missing``. See :ref:`bulk_insert_default`.
|
||||
- ``Prefer: max-affected``, See :ref:`prefer_max_affected`.
|
||||
- ``Prefer: tx``. See :ref:`prefer_tx`.
|
||||
- ``Prefer: params``. See :ref:`prefer_params`.
|
||||
|
||||
.. _prefer_handling:
|
||||
|
||||
Strict or Lenient Handling
|
||||
==========================
|
||||
|
||||
The server ignores unrecognized or unfulfillable preferences by default. You can control this behavior with the ``handling`` preference. It can take two values: ``lenient`` (the default) or ``strict``.
|
||||
|
||||
``handling=strict`` will throw an error if you specify invalid preferences. For instance:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl -i "http://localhost:3000/projects" \
|
||||
-H "Prefer: handling=strict, foo, bar"
|
||||
|
||||
.. code-block:: http
|
||||
|
||||
HTTP/1.1 400 Bad Request
|
||||
Content-Type: application/json; charset=utf-8
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
{
|
||||
"code": "PGRST122",
|
||||
"message": "Invalid preferences given with handling=strict",
|
||||
"details": "Invalid preferences: foo, bar",
|
||||
"hint": null
|
||||
}
|
||||
|
||||
|
||||
``handling=lenient`` ignores invalid preferences.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl -i "http://localhost:3000/projects" \
|
||||
-H "Prefer: handling=lenient, foo, bar"
|
||||
|
||||
.. code-block:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/json; charset=utf-8
|
||||
|
||||
.. _prefer_timezone:
|
||||
|
||||
Timezone
|
||||
========
|
||||
|
||||
The ``timezone`` preference allows you to change the `PostgreSQL timezone <https://www.postgresql.org/docs/current/runtime-config-client.html#GUC-TIMEZONE>`_. It accepts all time zones in `pg_timezone_names <https://www.postgresql.org/docs/current/view-pg-timezone-names.html>`_.
|
||||
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl -i "http://localhost:3000/timestamps" \
|
||||
-H "Prefer: timezone=America/Los_Angeles"
|
||||
|
||||
.. code-block:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/json; charset=utf-8
|
||||
Preference-Applied: timezone=America/Los_Angeles
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
[
|
||||
{"t":"2023-10-18T05:37:59.611-07:00"},
|
||||
{"t":"2023-10-18T07:37:59.611-07:00"},
|
||||
{"t":"2023-10-18T09:37:59.611-07:00"}
|
||||
]
|
||||
|
||||
For an invalid time zone, PostgREST returns values with the default time zone (configured on ``postgresql.conf`` or as a setting on the :ref:`authenticator <roles>`).
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl -i "http://localhost:3000/timestamps" \
|
||||
-H "Prefer: timezone=Jupiter/Red_Spot"
|
||||
|
||||
.. code-block:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/json; charset=utf-8
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
[
|
||||
{"t":"2023-10-18T12:37:59.611+00:00"},
|
||||
{"t":"2023-10-18T14:37:59.611+00:00"},
|
||||
{"t":"2023-10-18T16:37:59.611+00:00"}
|
||||
]
|
||||
|
||||
Note that there's no ``Preference-Applied`` in the response.
|
||||
|
||||
However, with ``handling=strict``, an invalid time zone preference will throw an :ref:`error <pgrst122>`.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl -i "http://localhost:3000/timestamps" \
|
||||
-H "Prefer: handling=strict, timezone=Jupiter/Red_Spot"
|
||||
|
||||
.. code-block:: http
|
||||
|
||||
HTTP/1.1 400 Bad Request
|
||||
|
||||
.. _prefer_return:
|
||||
|
||||
Return Representation
|
||||
=====================
|
||||
|
||||
The ``return`` preference can be used to obtain information about affected resource when it's :ref:`inserted <insert>`, :ref:`updated <update>` or :ref:`deleted <delete>`.
|
||||
This helps avoid a subsequent GET request.
|
||||
|
||||
Minimal
|
||||
-------
|
||||
|
||||
With ``Prefer: return=minimal``, no response body will be returned. This is the default mode for all write requests.
|
||||
|
||||
Headers Only
|
||||
------------
|
||||
|
||||
If the table has a primary key, the response can contain a :code:`Location` header describing where to find the new object by including the header :code:`Prefer: return=headers-only` in the request. Make sure that the table is not write-only, otherwise constructing the :code:`Location` header will cause a permissions error.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl -i "http://localhost:3000/projects" -X POST \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "Prefer: return=headers-only" \
|
||||
-d '{"id":33, "name": "x"}'
|
||||
|
||||
.. code-block:: http
|
||||
|
||||
HTTP/1.1 201 Created
|
||||
Location: /projects?id=eq.34
|
||||
Preference-Applied: return=headers-only
|
||||
|
||||
Full
|
||||
----
|
||||
|
||||
On the other end of the spectrum you can get the full created object back in the response to your request by including the header :code:`Prefer: return=representation`. That way you won't have to make another HTTP call to discover properties that may have been filled in on the server side. You can also apply the standard :ref:`v_filter` to these results.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl -i "http://localhost:3000/projects" -X POST \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "Prefer: return=representation" \
|
||||
-d '{"id":33, "name": "x"}'
|
||||
|
||||
.. code-block:: http
|
||||
|
||||
HTTP/1.1 201 Created
|
||||
Preference-Applied: return=representation
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
[
|
||||
{
|
||||
"id": 33,
|
||||
"name": "x"
|
||||
}
|
||||
]
|
||||
|
||||
.. _prefer_tx:
|
||||
|
||||
Transaction End Preference
|
||||
==========================
|
||||
|
||||
The ``tx`` preference can be set to specify if the :ref:`transaction <transactions>` will end in a COMMIT or ROLLBACK. This preference is not enabled by default but can be activated with :ref:`db-tx-end`.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl -i "http://localhost:3000/projects" -X POST \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "Prefer: tx=rollback, return=representation" \
|
||||
-d '{"name": "Project X"}'
|
||||
|
||||
.. code-block:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Preference-Applied: tx=rollback, return=representation
|
||||
|
||||
{"id": 35, "name": "Project X"}
|
||||
|
||||
|
||||
.. _prefer_max_affected:
|
||||
|
||||
Max Affected
|
||||
============
|
||||
|
||||
You can set a limit to the amount of resources affected in a request by sending ``max-affected`` preference. This feature works in combination with ``handling=strict`` preference. ``max-affected`` would be ignored with lenient handling. The "affected resources" are the number of rows returned by ``DELETE`` and ``PATCH`` requests. This is also supported through ``RPC`` calls.
|
||||
|
||||
To illustrate the use of this preference, consider the following scenario where the ``items`` table contains 14 rows.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl -i "http://localhost:3000/items?id=lt.15 -X DELETE \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "Prefer: handling=strict, max-affected=10"
|
||||
|
||||
.. code-block:: http
|
||||
|
||||
HTTP/1.1 400 Bad Request
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
{
|
||||
"code": "PGRST124",
|
||||
"message": "Query result exceeds max-affected preference constraint",
|
||||
"details": "The query affects 14 rows",
|
||||
"hint": null
|
||||
}
|
||||
|
||||
.. _prefer_params:
|
||||
|
||||
Single JSON object as Function Parameter
|
||||
----------------------------------------
|
||||
|
||||
.. warning::
|
||||
|
||||
Using this preference is **deprecated** in favor of :ref:`function_single_json`.
|
||||
|
||||
:code:`Prefer: params=single-object` allows sending the JSON request body as the single argument of a :ref:`function <functions>`.
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
CREATE FUNCTION mult_them(param json) RETURNS int AS $$
|
||||
SELECT (param->>'x')::int * (param->>'y')::int
|
||||
$$ LANGUAGE SQL;
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3000/rpc/mult_them" \
|
||||
-X POST -H "Content-Type: application/json" \
|
||||
-H "Prefer: params=single-object" \
|
||||
-d '{ "x": 4, "y": 2 }'
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
8
|
||||
@@ -57,11 +57,11 @@ For example, consider a database of films and their awards:
|
||||
language text
|
||||
);
|
||||
|
||||
CREATE TABLE technical_specs(
|
||||
film_id INT REFERENCES films UNIQUE,
|
||||
runtime TIME,
|
||||
camera TEXT,
|
||||
sound TEXT
|
||||
create table technical_specs(
|
||||
film_id int references films(id) primary key,
|
||||
runtime time,
|
||||
camera text,
|
||||
sound text
|
||||
);
|
||||
|
||||
create table roles(
|
||||
@@ -91,15 +91,9 @@ Many-to-one relationships
|
||||
|
||||
Since ``films`` has a **foreign key** to ``directors``, this establishes a many-to-one relationship. This enables us to request all the films and the director for each film.
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
GET /films?select=title,directors(id,last_name) HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/films?select=title,directors(id,last_name)"
|
||||
curl "http://localhost:3000/films?select=title,directors(id,last_name)"
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
@@ -128,15 +122,9 @@ Note that the embedded ``directors`` is returned as a JSON object because of the
|
||||
|
||||
Since the table name is plural, we can be more accurate by making it singular with an alias.
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
GET /films?select=title,director:directors(id,last_name) HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/films?select=title,director:directors(id,last_name)"
|
||||
curl "http://localhost:3000/films?select=title,director:directors(id,last_name)"
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
@@ -157,15 +145,9 @@ One-to-many relationships
|
||||
|
||||
The **foreign key reference** establishes the inverse one-to-many relationship. In this case, ``films`` returns as a JSON array because of the “to-many” end.
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
GET /directors?select=last_name,films(title) HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/directors?select=last_name,films(title)"
|
||||
curl "http://localhost:3000/directors?select=last_name,films(title)"
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
@@ -196,7 +178,7 @@ The join table determines many-to-many relationships. It must contain foreign ke
|
||||
|
||||
The join table is also detected if the composite key has additional columns.
|
||||
|
||||
.. code-block:: postgresql
|
||||
.. code-block:: postgres
|
||||
|
||||
create table roles(
|
||||
id int generated always as identity,
|
||||
@@ -206,15 +188,9 @@ The join table is also detected if the composite key has additional columns.
|
||||
, primary key(id, film_id, actor_id)
|
||||
);
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
GET /actors?select=first_name,last_name,films(title) HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/actors?select=first_name,last_name,films(title)"
|
||||
curl "http://localhost:3000/actors?select=first_name,last_name,films(title)"
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
@@ -238,24 +214,18 @@ One-to-one relationships are detected in two ways.
|
||||
- When the foreign key is a primary key as specified in the :ref:`sample film database <erd_film>`.
|
||||
- When the foreign key has a unique constraint.
|
||||
|
||||
.. code-block:: postgresql
|
||||
.. code-block:: postgres
|
||||
|
||||
CREATE TABLE technical_specs(
|
||||
film_id INT REFERENCES films UNIQUE,
|
||||
runtime TIME,
|
||||
camera TEXT,
|
||||
sound TEXT
|
||||
create table technical_specs(
|
||||
film_id int references films(id) unique,
|
||||
runtime time,
|
||||
camera text,
|
||||
sound text
|
||||
);
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
GET /films?select=title,technical_specs(camera) HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/films?select=title,technical_specs(camera)"
|
||||
curl "http://localhost:3000/films?select=title,technical_specs(camera)"
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
@@ -276,7 +246,7 @@ You can manually define relationships by using functions. This is useful for dat
|
||||
|
||||
Assuming there's a foreign table ``premieres`` that we want to relate to ``films``.
|
||||
|
||||
.. code-block:: postgresql
|
||||
.. code-block:: postgres
|
||||
|
||||
create foreign table premieres (
|
||||
id integer,
|
||||
@@ -292,15 +262,9 @@ Assuming there's a foreign table ``premieres`` that we want to relate to ``films
|
||||
The above function defines a relationship between ``premieres`` (the parameter) and ``films`` (the return type). Since there's a ``rows 1``, this defines a many-to-one relationship.
|
||||
The name of the function ``film`` is arbitrary and can be used to do the embedding:
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
GET /premieres?select=location,film(name) HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/premieres?select=location,film(name)"
|
||||
curl "http://localhost:3000/premieres?select=location,film(name)"
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
@@ -323,15 +287,9 @@ Now let's define the opposite one-to-many relationship.
|
||||
In this case there's an implicit ``ROWS 1000`` defined by PostgreSQL(`search "result_rows" on this PostgreSQL doc <https://www.postgresql.org/docs/current/sql-createfunction.html>`_).
|
||||
We consider any value greater than 1 as "many" so this defines a one-to-many relationship.
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
GET /films?select=name,premieres(name) HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/films?select=name,premieres(name)"
|
||||
curl "http://localhost:3000/films?select=name,premieres(name)"
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
@@ -417,15 +375,9 @@ For example, suppose you have the following ``orders`` and ``addresses`` tables:
|
||||
|
||||
Since the ``orders`` table has two foreign keys to the ``addresses`` table, a foreign key join is ambiguous and PostgREST will respond with an error:
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
GET /orders?select=*,addresses(*) HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/orders?select=*,addresses(*)" -i
|
||||
curl "http://localhost:3000/orders?select=*,addresses(*)" -i
|
||||
|
||||
|
||||
.. code-block:: http
|
||||
@@ -455,15 +407,12 @@ Since the ``orders`` table has two foreign keys to the ``addresses`` table, a fo
|
||||
To successfully join ``orders`` with ``addresses``, we can follow the error ``hint`` which tells us to add the foreign key name as ``!billing`` or ``!shipping``.
|
||||
Note that the foreign keys have been named explicitly in the :ref:`SQL definition above <multiple_m2o>`. To make the result clearer we'll also alias the tables:
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
# curl "http://localhost:3000/orders?select=name,billing_address:addresses!billing(name),shipping_address:addresses!shipping(name)"
|
||||
|
||||
GET /orders?select=name,billing_address:addresses!billing(name),shipping_address:addresses!shipping(name) HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/orders?select=name,billing_address:addresses!billing(name),shipping_address:addresses!shipping(name)"
|
||||
curl --get "http://localhost:3000/orders" \
|
||||
-d "select=name,billing_address:addresses!billing(name),shipping_address:addresses!shipping(name)"
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
@@ -486,15 +435,13 @@ Multiple One-To-Many
|
||||
|
||||
Let's take the tables from :ref:`multiple_m2o`. To get the opposite one-to-many relationship, we can also specify the foreign key name:
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
# curl "http://localhost:3000/addresses?select=name,billing_orders:orders!billing(name),shipping_orders!shipping(name)&id=eq.1"
|
||||
|
||||
GET /addresses?select=name,billing_orders:orders!billing(name),shipping_orders!shipping(name)&id=eq.1 HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/addresses?select=name,billing_orders:orders!billing(name),shipping_orders!shipping(name)&id=eq.1"
|
||||
curl --get "http://localhost:3000/addresses" \
|
||||
-d "select=name,billing_orders:orders!billing(name),shipping_orders!shipping(name)" \
|
||||
-d "id=eq.1"
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
@@ -538,7 +485,7 @@ Recursive One-To-One
|
||||
|
||||
To get either side of the Recursive One-To-One relationship, create the functions:
|
||||
|
||||
.. code-block:: postgresql
|
||||
.. code-block:: postgres
|
||||
|
||||
create or replace function predecessor(presidents) returns setof presidents rows 1 as $$
|
||||
select * from presidents where id = $1.predecessor_id
|
||||
@@ -550,15 +497,13 @@ To get either side of the Recursive One-To-One relationship, create the function
|
||||
|
||||
Now, to query a president with their predecessor and successor:
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
# curl "http://localhost:3000/presidents?select=last_name,predecessor(last_name),successor(last_name)&id=eq.2"
|
||||
|
||||
GET /presidents?select=last_name,predecessor(last_name),successor(last_name)&id=eq.2 HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/presidents?select=last_name,predecessor(last_name),successor(last_name)&id=eq.2"
|
||||
curl --get "http://localhost:3000/presidents" \
|
||||
-d "select=last_name,predecessor(last_name),successor(last_name)" \
|
||||
-d "id=eq.2"
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
@@ -596,7 +541,7 @@ Recursive One-To-Many
|
||||
|
||||
To get the One-To-Many embedding, that is, the supervisors with their supervisees, create a function like this one:
|
||||
|
||||
.. code-block:: postgresql
|
||||
.. code-block:: postgres
|
||||
|
||||
create or replace function supervisees(employees) returns setof employees as $$
|
||||
select * from employees where supervisor_id = $1.id
|
||||
@@ -604,15 +549,13 @@ To get the One-To-Many embedding, that is, the supervisors with their supervisee
|
||||
|
||||
Now, the query would be:
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
# curl "http://localhost:3000/employees?select=last_name,supervisees(last_name)&id=eq.1"
|
||||
|
||||
GET /employees?select=last_name,supervisees(last_name)&id=eq.1 HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/employees?select=last_name,supervisees(last_name)&id=eq.1"
|
||||
curl --get "http://localhost:3000/employees" \
|
||||
-d "select=last_name,supervisees(last_name)" \
|
||||
-d "id=eq.1"
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
@@ -634,7 +577,7 @@ Recursive Many-To-One
|
||||
Let's take the same ``employees`` table from :ref:`recursive_o2m_embed`.
|
||||
To get the Many-To-One relationship, that is, the employees with their respective supervisor, you need to create a function like this one:
|
||||
|
||||
.. code-block:: postgresql
|
||||
.. code-block:: postgres
|
||||
|
||||
create or replace function supervisor(employees) returns setof employees rows 1 as $$
|
||||
select * from employees where id = $1.supervisor_id
|
||||
@@ -642,15 +585,13 @@ To get the Many-To-One relationship, that is, the employees with their respectiv
|
||||
|
||||
Then, the query would be:
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
# curl "http://localhost:3000/employees?select=last_name,supervisor(last_name)&id=eq.3"
|
||||
|
||||
GET /employees?select=last_name,supervisor(last_name)&id=eq.3 HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/employees?select=last_name,supervisor(last_name)&id=eq.3"
|
||||
curl --get "http://localhost:3000/employees" \
|
||||
-d "select=last_name,supervisor(last_name)" \
|
||||
-d "id=eq.3"
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
@@ -692,7 +633,7 @@ Recursive Many-To-Many
|
||||
|
||||
To get all the subscribers of a user as well as the ones they're following, define these functions:
|
||||
|
||||
.. code-block:: postgresql
|
||||
.. code-block:: postgres
|
||||
|
||||
create or replace function subscribers(users) returns setof users as $$
|
||||
select u.*
|
||||
@@ -712,15 +653,13 @@ To get all the subscribers of a user as well as the ones they're following, defi
|
||||
|
||||
Then, the request would be:
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
# curl "http://localhost:3000/users?select=username,subscribers(username),following(username)&id=eq.4"
|
||||
|
||||
GET /users?select=username,subscribers(username),following(username)&id=eq.4 HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/users?select=username,subscribers(username),following(username)&id=eq.4"
|
||||
curl --get "http://localhost:3000/users" \
|
||||
-d "select=username,subscribers(username),following(username)" \
|
||||
-d "id=eq.4"
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
@@ -773,15 +712,13 @@ For example, let's create the ``box_office`` partitioned table that has the gros
|
||||
|
||||
Since it contains the ``films_id`` foreign key, it is possible to join ``box_office`` and ``films``:
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
# curl "http://localhost:3000/box_office?select=bo_date,gross_revenue,films(title)&gross_revenue=gte.1000000"
|
||||
|
||||
GET /box_office?select=bo_date,gross_revenue,films(title)&gross_revenue=gte.1000000 HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/box_office?select=bo_date,gross_revenue,films(title)&gross_revenue=gte.1000000"
|
||||
curl --get "http://localhost:3000/box_office" \
|
||||
-d "select=bo_date,gross_revenue,films(title)" \
|
||||
-d "gross_revenue=gte.1000000"
|
||||
|
||||
.. note::
|
||||
|
||||
@@ -814,15 +751,13 @@ For instance, the following view has ``nominations``, ``films`` and ``competitio
|
||||
|
||||
Since this view contains ``nominations.film_id``, which has a **foreign key** relationship to ``films``, then we can join the ``films`` table. Similarly, because the view contains ``films.id``, then we can also join the ``roles`` and the ``actors`` tables (the last one in a many-to-many relationship):
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
# curl "http://localhost:3000/nominations_view?select=film_title,films(language),roles(character),actors(last_name,first_name)&rank=eq.5"
|
||||
|
||||
GET /nominations_view?select=film_title,films(language),roles(character),actors(last_name,first_name)&rank=eq.5 HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/nominations_view?select=film_title,films(language),roles(character),actors(last_name,first_name)&rank=eq.5"
|
||||
curl --get "http://localhost:3000/nominations_view" \
|
||||
-d "select=film_title,films(language),roles(character),actors(last_name,first_name)" \
|
||||
-d "rank=eq.5"
|
||||
|
||||
It's also possible to foreign key join `Materialized Views <https://www.postgresql.org/docs/current/rules-materializedviews.html>`_.
|
||||
|
||||
@@ -843,16 +778,16 @@ Foreign Key Joins on Chains of Views
|
||||
|
||||
Views can also depend on other views, which in turn depend on the actual base table. For PostgREST to pick up those chains recursively to any depth, all the views must be in the search path, so either in the exposed schema (:ref:`db-schemas`) or in one of the schemas set in :ref:`db-extra-search-path`. This does not apply to the base table, which could be in a private schema as well. See :ref:`schema_isolation` for more details.
|
||||
|
||||
.. _s_proc_embed:
|
||||
.. _function_embed:
|
||||
|
||||
Foreign Key Joins on Table-Valued Functions
|
||||
===========================================
|
||||
|
||||
If you have a :ref:`Stored Procedure <s_procs>` that returns a table type, you can do a Foreign Key join on the result.
|
||||
If you have a :ref:`Function <functions>` that returns a table type, you can do a Foreign Key join on the result.
|
||||
|
||||
Here's a sample function (notice the ``RETURNS SETOF films``).
|
||||
|
||||
.. code-block:: plpgsql
|
||||
.. code-block:: postgres
|
||||
|
||||
CREATE FUNCTION getallfilms() RETURNS SETOF films AS $$
|
||||
SELECT * FROM films;
|
||||
@@ -860,15 +795,13 @@ Here's a sample function (notice the ``RETURNS SETOF films``).
|
||||
|
||||
A request with ``directors`` embedded:
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
# curl "http://localhost:3000/rpc/getallfilms?select=title,directors(id,last_name)&title=like.*Workers*"
|
||||
|
||||
GET /rpc/getallfilms?select=title,directors(id,last_name)&title=like.*Workers* HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/rpc/getallfilms?select=title,directors(id,last_name)&title=like.*Workers*"
|
||||
curl --get "http://localhost:3000/rpc/getallfilms" \
|
||||
-d "select=title,directors(id,last_name)" \
|
||||
-d "title=like.*Workers*"
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
@@ -890,36 +823,20 @@ You can join related database objects after doing :ref:`insert`, :ref:`update` o
|
||||
|
||||
Say you want to insert a **film** and then get some of its attributes plus join its **director**.
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
POST /films?select=title,year,director:directors(first_name,last_name) HTTP/1.1
|
||||
Prefer: return=representation
|
||||
|
||||
{
|
||||
curl "http://localhost:3000/films?select=title,year,director:directors(first_name,last_name)" \
|
||||
-H "Prefer: return=representation" \
|
||||
-d @- << EOF
|
||||
{
|
||||
"id": 100,
|
||||
"director_id": 40,
|
||||
"title": "127 hours",
|
||||
"year": 2010,
|
||||
"rating": 7.6,
|
||||
"language": "english"
|
||||
}
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/films?select=title,year,director:directors(first_name,last_name)" \
|
||||
-H "Prefer: return=representation" \
|
||||
-d @- << EOF
|
||||
{
|
||||
"id": 100,
|
||||
"director_id": 40,
|
||||
"title": "127 hours",
|
||||
"year": 2010,
|
||||
"rating": 7.6,
|
||||
"language": "english"
|
||||
}
|
||||
EOF
|
||||
}
|
||||
EOF
|
||||
|
||||
Response:
|
||||
|
||||
@@ -941,15 +858,9 @@ Nested Embedding
|
||||
|
||||
If you want to embed through join tables but need more control on the intermediate resources, you can do nested embedding. For instance, you can request the Actors, their Roles and the Films for those Roles:
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
GET /actors?select=roles(character,films(title,year)) HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/actors?select=roles(character,films(title,year))"
|
||||
curl "http://localhost:3000/actors?select=roles(character,films(title,year))"
|
||||
|
||||
.. _embed_filters:
|
||||
|
||||
@@ -958,77 +869,65 @@ Embedded Filters
|
||||
|
||||
Embedded resources can be shaped similarly to their top-level counterparts. To do so, prefix the query parameters with the name of the embedded resource. For instance, to order the actors in each film:
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
# curl "http://localhost:3000/films?select=*,actors(*)&actors.order=last_name,first_name"
|
||||
|
||||
GET /films?select=*,actors(*)&actors.order=last_name,first_name HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/films?select=*,actors(*)&actors.order=last_name,first_name"
|
||||
curl --get "http://localhost:3000/films" \
|
||||
-d "select=*,actors(*)" \
|
||||
-d "actors.order=last_name,first_name"
|
||||
|
||||
This sorts the list of actors in each film but does *not* change the order of the films themselves. To filter the roles returned with each film:
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
# curl "http://localhost:3000/films?select=*,roles(*)&roles.character=in.(Chico,Harpo,Groucho)"
|
||||
|
||||
GET /films?select=*,roles(*)&roles.character=in.(Chico,Harpo,Groucho) HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/films?select=*,roles(*)&roles.character=in.(Chico,Harpo,Groucho)"
|
||||
curl --get "http://localhost:3000/films" \
|
||||
-d "select=*,roles(*)" \
|
||||
-d "roles.character=in.(Chico,Harpo,Groucho)"
|
||||
|
||||
Once again, this restricts the roles included to certain characters but does not filter the films in any way. Films without any of those characters would be included along with empty character lists.
|
||||
|
||||
An ``or`` filter can be used for a similar operation:
|
||||
An ``or`` filter can be used for a similar operation:
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
# curl "http://localhost:3000/films?select=*,roles(*)&roles.or=(character.eq.Gummo,character.eq.Zeppo)"
|
||||
|
||||
GET /films?select=*,roles(*)&roles.or=(character.eq.Gummo,character.eq.Zeppo) HTTP/1.1
|
||||
curl --get "http://localhost:3000/films" \
|
||||
-d "select=*,roles(*)" \
|
||||
-d "roles.or=(character.eq.Gummo,character.eq.Zeppo)"
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/films?select=*,roles(*)&roles.or=(character.eq.Gummo,character.eq.Zeppo)"
|
||||
However, this only works for columns inside ``roles``. See :ref:`how to use "or" across multiple resources <or_embed_rels>`.
|
||||
|
||||
Limit and offset operations are possible:
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
# curl "http://localhost:3000/films?select=*,actors(*)&actors.limit=10&actors.offset=2"
|
||||
|
||||
GET /films?select=*,actors(*)&actors.limit=10&actors.offset=2 HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/films?select=*,actors(*)&actors.limit=10&actors.offset=2"
|
||||
curl --get "http://localhost:3000/films" \
|
||||
-d "select=*,actors(*)" \
|
||||
-d "actors.limit=10" \
|
||||
-d "actors.offset=2"
|
||||
|
||||
Embedded resources can be aliased and filters can be applied on these aliases:
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
# curl "http://localhost:3000/films?select=*,actors(*)&actors.limit=10&actors.offset=2"
|
||||
|
||||
GET /films?select=*,90_comps:competitions(name),91_comps:competitions(name)&90_comps.year=eq.1990&91_comps.year=eq.1991 HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/films?select=*,90_comps:competitions(name),91_comps:competitions(name)&90_comps.year=eq.1990&91_comps.year=eq.1991"
|
||||
curl --get "http://localhost:3000/films" \
|
||||
-d "select=*,90_comps:competitions(name),91_comps:competitions(name)" \
|
||||
-d "90_comps.year=eq.1990" \
|
||||
-d "91_comps.year=eq.1991"
|
||||
|
||||
Filters can also be applied on nested embedded resources:
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
GET /films?select=*,roles(*,actors(*))&roles.actors.order=last_name&roles.actors.first_name=like.*Tom* HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/films?select=*,roles(*,actors(*))&roles.actors.order=last_name&roles.actors.first_name=like.*Tom*"
|
||||
curl "http://localhost:3000/films?select=*,roles(*,actors(*))&roles.actors.order=last_name&roles.actors.first_name=like.*Tom*"
|
||||
|
||||
The result will show the nested actors named Tom and order them by last name. Aliases can also be used instead of the resource names to filter the nested tables.
|
||||
|
||||
@@ -1039,15 +938,13 @@ Top-level Filtering
|
||||
|
||||
By default, :ref:`embed_filters` don't change the top-level resource(``films``) rows at all:
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
# curl "http://localhost:3000/films?select=title,actors(first_name,last_name)&actors.first_name=eq.Jehanne
|
||||
|
||||
GET /films?select=title,actors(first_name,last_name)&actors.first_name=eq.Jehanne HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/films?select=title,actors(first_name,last_name)&actors.first_name=eq.Jehanne
|
||||
curl --get "http://localhost:3000/films" \
|
||||
-d "select=title,actors(first_name,last_name)" \
|
||||
-d "actors.first_name=eq.Jehanne"
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
@@ -1073,15 +970,13 @@ By default, :ref:`embed_filters` don't change the top-level resource(``films``)
|
||||
|
||||
In order to filter the top level rows you need to add ``!inner`` to the embedded resource. For instance, to get **only** the films that have an actor named ``Jehanne``:
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
# curl "http://localhost:3000/films?select=title,actors!inner(first_name,last_name)&actors.first_name=eq.Jehanne"
|
||||
|
||||
GET /films?select=title,actors!inner(first_name,last_name)&actors.first_name=eq.Jehanne HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/films?select=title,actors!inner(first_name,last_name)&actors.first_name=eq.Jehanne"
|
||||
curl --get "http://localhost:3000/films" \
|
||||
-d "select=title,actors!inner(first_name,last_name)" \
|
||||
-d "actors.first_name=eq.Jehanne"
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
@@ -1106,40 +1001,94 @@ Null filtering on the embedded resources can behave the same as ``!inner``. Whil
|
||||
|
||||
For example, doing ``actors=not.is.null`` returns the same result as ``actors!inner(*)``:
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
# curl "http://localhost:3000/films?select=title,actors(*)&actors=not.is.null"
|
||||
|
||||
GET /films?select=title,actors(*)&actors=not.is.null HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/films?select=title,actors(*)&actors=not.is.null"
|
||||
curl --get "http://localhost:3000/films" \
|
||||
-d "select=title,actors(*)" \
|
||||
-d "actors=not.is.null"
|
||||
|
||||
The ``is.null`` filter can be used in embedded resources to perform an anti-join. To get all the films that do not have any nominations:
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
# curl "http://localhost:3000/films?select=title,nominations()&nominations=is.null"
|
||||
|
||||
GET /films?select=title,nominations()&nominations=is.null HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/films?select=title,nominations()&nominations=is.null"
|
||||
curl --get "http://localhost:3000/films" \
|
||||
-d "select=title,nominations()" \
|
||||
-d "nominations=is.null"
|
||||
|
||||
|
||||
Both ``is.null`` and ``not.is.null`` can be included inside the `or` operator. For instance, to get the films that have no actors **or** directors registered yet:
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
# curl "http://localhost:3000/films?select=title,nominations()&nominations=is.null"
|
||||
|
||||
GET /films?select=title,actors(*),directors(*)&or=(actors.is.null,directors.is.null) HTTP/1.1
|
||||
curl --get "http://localhost:3000/films" \
|
||||
-d select=title,actors(*),directors(*)" \
|
||||
-d "or=(actors.is.null,directors.is.null)"
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
.. _or_embed_rels:
|
||||
|
||||
curl "http://localhost:3000/films?select=title,actors(*),directors(*)&or=(actors.is.null,directors.is.null)"
|
||||
OR filtering across Embedded Resources
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
You can also use ``not.is.null`` to make an ``or`` filter across multiple resources.
|
||||
For instance, to show the films with actors **or** directors named John:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
# curl "http://localhost:3000/films?select=title,actors(),directors()&directors.first_name=eq.John&actors.first_name=eq.John&or=(directors.not.is.null,actors.not.is.null)"
|
||||
|
||||
curl --get "http://localhost:3000/films" \
|
||||
-d "select=title,actors(),directors()" \
|
||||
-d "directors.first_name=eq.John" \
|
||||
-d "actors.first_name=eq.John" \
|
||||
-d "or=(directors.not.is.null,actors.not.is.null)"
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
[
|
||||
{ "title": "Pulp Fiction" },
|
||||
{ "title": "The Thing" },
|
||||
".."
|
||||
]
|
||||
|
||||
Here, we use :ref:`empty embeds <empty_embed>` because retrieving their info would be restricted by the filters.
|
||||
For example, the ``directors`` embedding would return ``null`` if its ``first_name`` is not John.
|
||||
To solve this, you need to add extra embedded resources and use the empty ones for filtering.
|
||||
From the above example:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
# curl "http://localhost:3000/films?select=title,act:actors(),dir:directors(),actors(first_name),directors(first_name)&dir.first_name=eq.John&act.first_name=eq.John&or=(dir.not.is.null,act.not.is.null)"
|
||||
|
||||
curl --get "http://localhost:3000/films" \
|
||||
# We need to use aliases like "act" and "dir" to filter the empty embeds
|
||||
-d "select=title,act:actors(),dir:directors(),actors(first_name),directors(first_name)" \
|
||||
-d "dir.first_name=eq.John" \
|
||||
-d "act.first_name=eq.John" \
|
||||
-d "or=(dir.not.is.null,act.not.is.null)"
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
[
|
||||
{
|
||||
"title": "Pulp Fiction",
|
||||
"actors": [
|
||||
{ "first_name": "John" },
|
||||
{ "first_name": "Samuel" },
|
||||
{ "first_name": "Uma" },
|
||||
".."
|
||||
]
|
||||
"directors": {
|
||||
"first_name": "Quentin"
|
||||
}
|
||||
},
|
||||
".."
|
||||
]
|
||||
|
||||
.. _empty_embed:
|
||||
|
||||
@@ -1150,15 +1099,14 @@ You can leave an embedded resource empty, this helps with filtering in some case
|
||||
|
||||
To filter the films by actors but not include them:
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
# curl "http://localhost:3000/films?select=title,actors()&actors.first_name=eq.Jehanne&actors=not.is.null"
|
||||
|
||||
GET /films?select=title,actors()&actors.first_name=eq.Jehanne&actors=not.is.null HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/films?select=title,actors()&actors.first_name=eq.Jehanne&actors=not.is.null"
|
||||
curl --get "http://localhost:3000/films" \
|
||||
-d "select=title,actors()" \
|
||||
-d "actors.first_name=eq.Jehanne" \
|
||||
-d "actors=not.is.null"
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
@@ -1177,15 +1125,13 @@ On :ref:`Many-to-One <many-to-one>` and :ref:`One-to-One <one-to-one>` relations
|
||||
|
||||
For example, to arrange the films in descending order using the director's last name.
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
# curl "http://localhost:3000/films?select=title,directors(last_name)&order=directors(last_name).desc"
|
||||
|
||||
GET /films?select=title,directors(last_name)&order=directors(last_name).desc HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/films?select=title,directors(last_name)&order=directors(last_name).desc"
|
||||
curl --get "http://localhost:3000/films" \
|
||||
-d "select=title,directors(last_name)" \
|
||||
-d "order=directors(last_name).desc"
|
||||
|
||||
.. _spread_embed:
|
||||
|
||||
@@ -1194,15 +1140,13 @@ Spread embedded resource
|
||||
|
||||
On many-to-one and one-to-one relationships, you can "spread" the embedded resource. That is, remove the surrounding JSON object for the embedded resource columns.
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
# curl "http://localhost:3000/films?select=title,...directors(director_last_name:last_name)&title=like.*Workers*"
|
||||
|
||||
GET /films?select=title,...directors(director_last_name:last_name)&title=like.*Workers* HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/films?select=title,...directors(director_last_name:last_name)&title=like.*Workers*"
|
||||
curl --get "http://localhost:3000/films" \
|
||||
-d "select=title,...directors(director_last_name:last_name)" \
|
||||
-d "title=like.*Workers*"
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
@@ -1217,15 +1161,13 @@ Note that there is no ``"directors"`` object. Also the embed columns can be alia
|
||||
|
||||
You can use this to get the columns of a join table in a many-to-many relationship. For instance, to get films and its actors, but including the ``character`` column from the roles table:
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
# curl "http://localhost:3000/films?select=title,actors:roles(character,...actors(first_name,last_name))&title=like.*Lighthouse*"
|
||||
|
||||
GET /films?select=title,actors:roles(character,...actors(first_name,last_name))&title=like.*Lighthouse* HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/films?select=title,actors:roles(character,...actors(first_name,last_name))&title=like.*Lighthouse*"
|
||||
curl --get "http://localhost:3000/films" \
|
||||
-d "select=title,actors:roles(character,...actors(first_name,last_name))" \
|
||||
-d "title=like.*Lighthouse*"
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
@@ -1245,4 +1187,3 @@ You can use this to get the columns of a join table in a many-to-many relationsh
|
||||
.. note::
|
||||
|
||||
The spread operator ``...`` is borrowed from the Javascript `spread syntax <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax>`_.
|
||||
|
||||
|
||||
@@ -11,27 +11,42 @@ Response Format
|
||||
|
||||
Use the Accept request header to specify the acceptable format (or formats) for the response:
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
curl "http://localhost:3000/people" \
|
||||
-H "Accept: application/json"
|
||||
|
||||
GET /people HTTP/1.1
|
||||
Accept: application/json
|
||||
.. _builtin_media:
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
Builtin Media Type Handlers
|
||||
===========================
|
||||
|
||||
curl "http://localhost:3000/people" \
|
||||
-H "Accept: application/json"
|
||||
Builtin handlers are offered for common standard media types.
|
||||
|
||||
For tables and views the current possibilities are:
|
||||
* ``text/csv`` and ``application/json``, for all API endpoints. See :ref:`tables_views` and :ref:`functions`.
|
||||
* ``application/openapi+json``, for the root endpoint. See :ref:`open-api`.
|
||||
* ``application/geo+json``, see :ref:`ww_postgis`.
|
||||
* ``*/*``, resolves to ``application/json`` for API endpoints and to ``application/openapi+json`` for the root endpoint.
|
||||
|
||||
* ``*/*``
|
||||
* ``text/csv``
|
||||
* ``application/json``
|
||||
* ``application/openapi+json``
|
||||
* ``application/geo+json``
|
||||
The following vendor media types handlers are also supported.
|
||||
|
||||
The server will default to JSON for API endpoints and OpenAPI on the root.
|
||||
* ``application/vnd.pgrst.plan``, see :ref:`explain_plan`.
|
||||
* ``application/vnd.pgrst.object`` and ``application/vnd.pgrst.array``, see :ref:`singular_plural` and :ref:`stripped_nulls`.
|
||||
|
||||
Any unrecognized media type will throw an error.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
curl "http://localhost:3000/people" \
|
||||
-H "Accept: unknown/unknown"
|
||||
|
||||
.. code-block:: http
|
||||
|
||||
HTTP/1.1 415 Unsupported Media Type
|
||||
|
||||
{"code":"PGRST107","details":null,"hint":null,"message":"None of these media types are available: unknown/unknown"}
|
||||
|
||||
To extend the accepted media types, you can use :ref:`custom_media`.
|
||||
|
||||
.. _singular_plural:
|
||||
|
||||
@@ -48,17 +63,10 @@ By default PostgREST returns all JSON results in an array, even when there is on
|
||||
|
||||
This can be inconvenient for client code. To return the first result as an object unenclosed by an array, specify :code:`vnd.pgrst.object` as part of the :code:`Accept` header
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
GET /items?id=eq.1 HTTP/1.1
|
||||
Accept: application/vnd.pgrst.object+json
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/items?id=eq.1" \
|
||||
-H "Accept: application/vnd.pgrst.object+json"
|
||||
curl "http://localhost:3000/items?id=eq.1" \
|
||||
-H "Accept: application/vnd.pgrst.object+json"
|
||||
|
||||
This returns
|
||||
|
||||
@@ -85,6 +93,8 @@ When a singular response is requested but no entries are found, the server respo
|
||||
|
||||
Admittedly PostgREST could detect when there is an equality condition holding on all columns constituting the primary key and automatically convert to singular. However this could lead to a surprising change of format that breaks unwary client code just by filtering on an extra column. Instead we allow manually specifying singular vs plural to decouple that choice from the URL format.
|
||||
|
||||
.. _stripped_nulls:
|
||||
|
||||
Stripped Nulls
|
||||
--------------
|
||||
|
||||
@@ -98,19 +108,12 @@ By default PostgREST returns all JSON null values. For example, requesting ``/pr
|
||||
{ "id": 13, "name": "Y", "client_id": null, "another_col": null }
|
||||
]
|
||||
|
||||
On large result sets, the unused keys with ``null`` values can waste bandwith unnecessarily. To remove them, specify ``nulls=stripped`` as a parameter of ``application/vnd.pgrst.array``:
|
||||
On large result sets, the unused keys with ``null`` values can waste bandwidth unnecessarily. To remove them, specify ``nulls=stripped`` as a parameter of ``application/vnd.pgrst.array``:
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
GET /projects?id=gt.10 HTTP/1.1
|
||||
Accept: application/vnd.pgrst.array+json;nulls=stripped
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/projects?id=gt.10" \
|
||||
-H "Accept: application/vnd.pgrst.array+json;nulls=stripped"
|
||||
curl "http://localhost:3000/projects?id=gt.10" \
|
||||
-H "Accept: application/vnd.pgrst.array+json;nulls=stripped"
|
||||
|
||||
This returns
|
||||
|
||||
@@ -122,72 +125,6 @@ This returns
|
||||
{ "id": 13, "name": "Y"}
|
||||
]
|
||||
|
||||
.. _scalar_return_formats:
|
||||
|
||||
Scalar Function Response Format
|
||||
-------------------------------
|
||||
|
||||
In the special case of a :ref:`scalar_functions` there are three additional formats:
|
||||
|
||||
* ``application/octet-stream``
|
||||
* ``text/plain``
|
||||
* ``text/xml``
|
||||
|
||||
Example 1: If you want to return raw binary data from a :code:`bytea` column, you must specify :code:`application/octet-stream` as part of the :code:`Accept` header
|
||||
and select a single column :code:`?select=bin_data`.
|
||||
|
||||
.. tabs::
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
GET /items?select=bin_data&id=eq.1 HTTP/1.1
|
||||
Accept: application/octet-stream
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/items?select=bin_data&id=eq.1" \
|
||||
-H "Accept: application/octet-stream"
|
||||
|
||||
Example 2: You can request XML output when having a scalar function that returns a type of ``text/xml``. You are not forced to use select for this case.
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
CREATE FUNCTION generate_xml_content(..) RETURNS xml ..
|
||||
|
||||
.. tabs::
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
POST /rpc/generate_xml_content HTTP/1.1
|
||||
Accept: text/xml
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/rpc/generate_xml_content" \
|
||||
-X POST -H "Accept: text/xml"
|
||||
|
||||
Example 3: If the stored procedure returns non-scalar values, you need to do a :code:`select` in the same way as for GET binary output.
|
||||
|
||||
.. code-block:: sql
|
||||
|
||||
CREATE FUNCTION get_descriptions(..) RETURNS SETOF TABLE(id int, description text) ..
|
||||
|
||||
.. tabs::
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
POST /rpc/get_descriptions?select=description HTTP/1.1
|
||||
Accept: text/plain
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/rpc/get_descriptions?select=description" \
|
||||
-X POST -H "Accept: text/plain"
|
||||
|
||||
.. note::
|
||||
|
||||
If more than one row would be returned the binary/plain-text/xml results will be concatenated with no delimiter.
|
||||
|
||||
.. _req_body:
|
||||
|
||||
Request Body
|
||||
@@ -199,12 +136,12 @@ The server handles the following request body media types:
|
||||
* ``application/x-www-form-urlencoded``
|
||||
* ``text/csv``
|
||||
|
||||
For :ref:`tables_views` this works on ``POST``, ``PATCH`` and ``PUT`` methods. For :ref:`s_procs`, it works on ``POST`` methods.
|
||||
For :ref:`tables_views` this works on ``POST``, ``PATCH`` and ``PUT`` methods. For :ref:`functions`, it works on ``POST`` methods.
|
||||
|
||||
For stored procedures there are three additional types:
|
||||
For functions there are three additional types:
|
||||
|
||||
* ``application/octet-stream``
|
||||
* ``text/plain``
|
||||
* ``text/xml``
|
||||
|
||||
See :ref:`s_proc_single_unnamed`.
|
||||
See :ref:`function_single_unnamed`.
|
||||
|
||||
@@ -42,59 +42,34 @@ GET/HEAD
|
||||
|
||||
For GET or HEAD, select the schema with ``Accept-Profile``.
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
GET /items HTTP/1.1
|
||||
Accept-Profile: tenant2
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/items" \
|
||||
-H "Accept-Profile: tenant2"
|
||||
curl "http://localhost:3000/items" \
|
||||
-H "Accept-Profile: tenant2"
|
||||
|
||||
Other methods
|
||||
~~~~~~~~~~~~~
|
||||
|
||||
For POST, PATCH, PUT and DELETE, select the schema with ``Content-Profile``.
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
curl "http://localhost:3000/items" \
|
||||
-X POST -H "Content-Type: application/json" \
|
||||
-H "Content-Profile: tenant2" \
|
||||
-d '{...}'
|
||||
|
||||
POST /items HTTP/1.1
|
||||
Content-Profile: tenant2
|
||||
|
||||
{...}
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/items" \
|
||||
-X POST -H "Content-Type: application/json" \
|
||||
-H "Content-Profile: tenant2" \
|
||||
-d '{...}'
|
||||
|
||||
You can also select the schema for :ref:`s_procs` and :ref:`open-api`.
|
||||
You can also select the schema for :ref:`functions` and :ref:`open-api`.
|
||||
|
||||
Restricted schemas
|
||||
~~~~~~~~~~~~~~~~~~
|
||||
|
||||
You can only switch to a schema included in :ref:`db-schemas`. Using another schema will result in an error:
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
GET /items HTTP/1.1
|
||||
Accept-Profile: tenant3
|
||||
|
||||
{...}
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/items" \
|
||||
-H "Accept-Profile: tenant3"
|
||||
curl "http://localhost:3000/items" \
|
||||
-H "Accept-Profile: tenant3"
|
||||
|
||||
.. code-block::
|
||||
|
||||
@@ -113,7 +88,7 @@ To add schemas dynamically, you can use :ref:`in_db_config` plus :ref:`config re
|
||||
|
||||
- If the schemas' names have a pattern, like a ``tenant_`` prefix, do:
|
||||
|
||||
.. code-block:: postgresql
|
||||
.. code-block:: postgres
|
||||
|
||||
create or replace function postgrest.pre_config()
|
||||
returns void as $$
|
||||
@@ -125,7 +100,7 @@ To add schemas dynamically, you can use :ref:`in_db_config` plus :ref:`config re
|
||||
|
||||
- If there's no name pattern but they're created with a particular role (``CREATE SCHEMA mine AUTHORIZATION joe``), do:
|
||||
|
||||
.. code-block:: postgresql
|
||||
.. code-block:: postgres
|
||||
|
||||
create or replace function postgrest.pre_config()
|
||||
returns void as $$
|
||||
@@ -137,7 +112,7 @@ To add schemas dynamically, you can use :ref:`in_db_config` plus :ref:`config re
|
||||
|
||||
- Otherwise, you might need to create a table that stores the allowed schemas.
|
||||
|
||||
.. code-block:: postgresql
|
||||
.. code-block:: postgres
|
||||
|
||||
create table postgrest.config (schemas text);
|
||||
|
||||
@@ -150,7 +125,7 @@ To add schemas dynamically, you can use :ref:`in_db_config` plus :ref:`config re
|
||||
|
||||
Then each time you add an schema, do:
|
||||
|
||||
.. code-block:: postgresql
|
||||
.. code-block:: postgres
|
||||
|
||||
NOTIFY pgrst, 'reload config';
|
||||
NOTIFY pgrst, 'reload schema';
|
||||
|
||||
@@ -1,489 +0,0 @@
|
||||
.. _s_procs:
|
||||
|
||||
Stored Procedures
|
||||
=================
|
||||
|
||||
*"A single resource can be the equivalent of a database stored procedure, with the power to abstract state changes over any number of storage items"* -- `Roy T. Fielding <http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven#comment-743>`_
|
||||
|
||||
Procedures can perform any operations allowed by PostgreSQL (read data, modify data, :ref:`raise errors <raise_error>`, and even DDL operations). Every stored procedure in the :ref:`exposed schema <schemas>` and accessible by the :ref:`active database role <roles>` is executable under the :code:`/rpc` prefix.
|
||||
|
||||
If they return table types, Stored Procedures can:
|
||||
|
||||
- Use all the same :ref:`read filters as Tables and Views <read>` (horizontal/vertical filtering, counts, limits, etc.).
|
||||
- Use :ref:`Resource Embedding <s_proc_embed>`, if the returned table type has relationships to other tables.
|
||||
|
||||
.. note::
|
||||
|
||||
Why the ``/rpc`` prefix? PostgreSQL allows a table or view to have the same name as a function. The prefix allows us to avoid routes collisions.
|
||||
|
||||
Calling with POST
|
||||
-----------------
|
||||
|
||||
To supply arguments in an API call, include a JSON object in the request payload. Each key/value of the object will become an argument.
|
||||
|
||||
For instance, assume we have created this function in the database.
|
||||
|
||||
.. code-block:: plpgsql
|
||||
|
||||
CREATE FUNCTION add_them(a integer, b integer)
|
||||
RETURNS integer AS $$
|
||||
SELECT a + b;
|
||||
$$ LANGUAGE SQL IMMUTABLE;
|
||||
|
||||
.. important::
|
||||
|
||||
Whenever you create or change a function you must refresh PostgREST's schema cache. See the section :ref:`schema_reloading`.
|
||||
|
||||
The client can call it by posting an object like
|
||||
|
||||
.. tabs::
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
POST /rpc/add_them HTTP/1.1
|
||||
|
||||
{ "a": 1, "b": 2 }
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/rpc/add_them" \
|
||||
-X POST -H "Content-Type: application/json" \
|
||||
-d '{ "a": 1, "b": 2 }'
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
3
|
||||
|
||||
.. note::
|
||||
|
||||
PostgreSQL converts identifier names to lowercase unless you quote them like:
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
CREATE FUNCTION "someFunc"("someParam" text) ...
|
||||
|
||||
Calling with GET
|
||||
----------------
|
||||
|
||||
If the function doesn't modify the database, it will also run under the GET method (see :ref:`access_mode`).
|
||||
|
||||
.. tabs::
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
GET /rpc/add_them?a=1&b=2 HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/rpc/add_them?a=1&b=2"
|
||||
|
||||
The function parameter names match the JSON object keys in the POST case, for the GET case they match the query parameters ``?a=1&b=2``.
|
||||
|
||||
.. _s_proc_single_json:
|
||||
|
||||
Functions with a single JSON parameter
|
||||
--------------------------------------
|
||||
|
||||
You can also call a function that takes a single parameter of type JSON by sending the header :code:`Prefer: params=single-object` with your request. That way the JSON request body will be used as the single argument.
|
||||
|
||||
.. code-block:: plpgsql
|
||||
|
||||
CREATE FUNCTION mult_them(param json) RETURNS int AS $$
|
||||
SELECT (param->>'x')::int * (param->>'y')::int
|
||||
$$ LANGUAGE SQL;
|
||||
|
||||
.. tabs::
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
POST /rpc/mult_them HTTP/1.1
|
||||
Prefer: params=single-object
|
||||
|
||||
{ "x": 4, "y": 2 }
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/rpc/mult_them" \
|
||||
-X POST -H "Content-Type: application/json" \
|
||||
-H "Prefer: params=single-object" \
|
||||
-d '{ "x": 4, "y": 2 }'
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
8
|
||||
|
||||
.. _s_proc_single_unnamed:
|
||||
|
||||
Functions with a single unnamed parameter
|
||||
-----------------------------------------
|
||||
|
||||
You can make a POST request to a function with a single unnamed parameter to send raw ``json/jsonb``, ``bytea``, ``text`` or ``xml`` data.
|
||||
|
||||
To send raw JSON, the function must have a single unnamed ``json`` or ``jsonb`` parameter and the header ``Content-Type: application/json`` must be included in the request.
|
||||
|
||||
.. code-block:: plpgsql
|
||||
|
||||
CREATE FUNCTION mult_them(json) RETURNS int AS $$
|
||||
SELECT ($1->>'x')::int * ($1->>'y')::int
|
||||
$$ LANGUAGE SQL;
|
||||
|
||||
.. tabs::
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
POST /rpc/mult_them HTTP/1.1
|
||||
Content-Type: application/json
|
||||
|
||||
{ "x": 4, "y": 2 }
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/rpc/mult_them" \
|
||||
-X POST -H "Content-Type: application/json" \
|
||||
-d '{ "x": 4, "y": 2 }'
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
8
|
||||
|
||||
.. note::
|
||||
|
||||
If an overloaded function has a single ``json`` or ``jsonb`` unnamed parameter, PostgREST will call this function as a fallback provided that no other overloaded function is found with the parameters sent in the POST request.
|
||||
|
||||
To send raw XML, the parameter type must be ``xml`` and the header ``Content-Type: text/xml`` must be included in the request.
|
||||
|
||||
To send raw binary, the parameter type must be ``bytea`` and the header ``Content-Type: application/octet-stream`` must be included in the request.
|
||||
|
||||
.. code-block:: plpgsql
|
||||
|
||||
CREATE TABLE files(blob bytea);
|
||||
|
||||
CREATE FUNCTION upload_binary(bytea) RETURNS void AS $$
|
||||
INSERT INTO files(blob) VALUES ($1);
|
||||
$$ LANGUAGE SQL;
|
||||
|
||||
.. tabs::
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
POST /rpc/upload_binary HTTP/1.1
|
||||
Content-Type: application/octet-stream
|
||||
|
||||
file_name.ext
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/rpc/upload_binary" \
|
||||
-X POST -H "Content-Type: application/octet-stream" \
|
||||
--data-binary "@file_name.ext"
|
||||
|
||||
.. code-block:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
|
||||
[ ... ]
|
||||
|
||||
To send raw text, the parameter type must be ``text`` and the header ``Content-Type: text/plain`` must be included in the request.
|
||||
|
||||
.. _s_procs_array:
|
||||
|
||||
Functions with array parameters
|
||||
-------------------------------
|
||||
|
||||
You can call a function that takes an array parameter:
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
create function plus_one(arr int[]) returns int[] as $$
|
||||
SELECT array_agg(n + 1) FROM unnest($1) AS n;
|
||||
$$ language sql;
|
||||
|
||||
.. tabs::
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
POST /rpc/plus_one HTTP/1.1
|
||||
Content-Type: application/json
|
||||
|
||||
{"arr": [1,2,3,4]}
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/rpc/plus_one" \
|
||||
-X POST -H "Content-Type: application/json" \
|
||||
-d '{"arr": [1,2,3,4]}'
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
[2,3,4,5]
|
||||
|
||||
For calling the function with GET, you can pass the array as an `array literal <https://www.postgresql.org/docs/current/arrays.html#ARRAYS-INPUT>`_,
|
||||
as in ``{1,2,3,4}``. Note that the curly brackets have to be urlencoded(``{`` is ``%7B`` and ``}`` is ``%7D``).
|
||||
|
||||
.. tabs::
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
GET /rpc/plus_one?arr=%7B1,2,3,4%7D' HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/rpc/plus_one?arr=%7B1,2,3,4%7D'"
|
||||
|
||||
.. note::
|
||||
|
||||
For versions prior to PostgreSQL 10, to pass a PostgreSQL native array on a POST payload, you need to quote it and use an array literal:
|
||||
|
||||
.. tabs::
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
POST /rpc/plus_one HTTP/1.1
|
||||
|
||||
{ "arr": "{1,2,3,4}" }
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/rpc/plus_one" \
|
||||
-X POST -H "Content-Type: application/json" \
|
||||
-d '{ "arr": "{1,2,3,4}" }'
|
||||
|
||||
In these versions we recommend using function parameters of type JSON to accept arrays from the client.
|
||||
|
||||
.. _s_procs_variadic:
|
||||
|
||||
Variadic functions
|
||||
------------------
|
||||
|
||||
You can call a variadic function by passing a JSON array in a POST request:
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
create function plus_one(variadic v int[]) returns int[] as $$
|
||||
SELECT array_agg(n + 1) FROM unnest($1) AS n;
|
||||
$$ language sql;
|
||||
|
||||
.. tabs::
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
POST /rpc/plus_one HTTP/1.1
|
||||
Content-Type: application/json
|
||||
|
||||
{"v": [1,2,3,4]}
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/rpc/plus_one" \
|
||||
-X POST -H "Content-Type: application/json" \
|
||||
-d '{"v": [1,2,3,4]}'
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
[2,3,4,5]
|
||||
|
||||
In a GET request, you can repeat the same parameter name:
|
||||
|
||||
.. tabs::
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
GET /rpc/plus_one?v=1&v=2&v=3&v=4 HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/rpc/plus_one?v=1&v=2&v=3&v=4"
|
||||
|
||||
Repeating also works in POST requests with ``Content-Type: application/x-www-form-urlencoded``:
|
||||
|
||||
.. tabs::
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
POST /rpc/plus_one HTTP/1.1
|
||||
Content-Type: application/x-www-form-urlencoded
|
||||
|
||||
v=1&v=2&v=3&v=4
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/rpc/plus_one" \
|
||||
-X POST -H "Content-Type: application/x-www-form-urlencoded" \
|
||||
-d 'v=1&v=2&v=3&v=4'
|
||||
|
||||
Table-Valued functions
|
||||
----------------------
|
||||
|
||||
A function that returns a table type can be filtered using the same filters as :ref:`tables and views <tables_views>`. They can also use :ref:`Resource Embedding <s_proc_embed>`.
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
CREATE FUNCTION best_films_2017() RETURNS SETOF films ..
|
||||
|
||||
.. tabs::
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
GET /rpc/best_films_2017?select=title,director:directors(*) HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/rpc/best_films_2017?select=title,director:directors(*)"
|
||||
|
||||
.. tabs::
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
GET /rpc/best_films_2017?rating=gt.8&order=title.desc HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/rpc/best_films_2017?rating=gt.8&order=title.desc"
|
||||
|
||||
.. _function_inlining:
|
||||
|
||||
Function Inlining
|
||||
~~~~~~~~~~~~~~~~~
|
||||
|
||||
A function that follows the `rules for inlining <https://wiki.postgresql.org/wiki/Inlining_of_SQL_functions#Inlining_conditions_for_table_functions>`_ will also inline :ref:`filters <h_filter>`, :ref:`order <ordering>` and :ref:`limits <limits>`.
|
||||
|
||||
For example, for the following function:
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
create function getallprojects() returns setof projects
|
||||
language sql stable
|
||||
as $$
|
||||
select * from projects;
|
||||
$$;
|
||||
|
||||
Let's get its :ref:`explain_plan` when calling it with filters applied:
|
||||
|
||||
.. tabs::
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
GET /rpc/getallprojects?id=eq.1 HTTP/1.1
|
||||
Accept: application/vnd.pgrst.plan
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/rpc/getallprojects?id=eq.1" \
|
||||
-H "Accept: application/vnd.pgrst.plan"
|
||||
|
||||
.. code-block:: psql
|
||||
|
||||
Aggregate (cost=8.18..8.20 rows=1 width=112)
|
||||
-> Index Scan using projects_pkey on projects (cost=0.15..8.17 rows=1 width=40)
|
||||
Index Cond: (id = 1)
|
||||
|
||||
Notice there's no "Function Scan" node in the plan, which tells us it has been inlined.
|
||||
|
||||
.. _scalar_functions:
|
||||
|
||||
Scalar functions
|
||||
----------------
|
||||
|
||||
PostgREST will detect if the function is scalar or table-valued and will shape the response format accordingly:
|
||||
|
||||
.. tabs::
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
GET /rpc/add_them?a=1&b=2 HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/rpc/add_them?a=1&b=2"
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
3
|
||||
|
||||
.. tabs::
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
GET /rpc/best_films_2017 HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/rpc/best_films_2017"
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
[
|
||||
{ "title": "Okja", "rating": 7.4},
|
||||
{ "title": "Call me by your name", "rating": 8},
|
||||
{ "title": "Blade Runner 2049", "rating": 8.1}
|
||||
]
|
||||
|
||||
To manually choose a return format such as binary, plain text or XML, see the section :ref:`scalar_return_formats`.
|
||||
|
||||
.. _untyped_functions:
|
||||
|
||||
Untyped functions
|
||||
-----------------
|
||||
|
||||
Functions that return ``record`` or ``SETOF record`` are supported:
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
create function projects_setof_record() returns setof record as $$
|
||||
select * from projects;
|
||||
$$ language sql;
|
||||
|
||||
.. tabs::
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
GET /rpc/projects_setof_record HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/rpc/projects_setof_record"
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
[{"id":1,"name":"Windows 7","client_id":1},
|
||||
{"id":2,"name":"Windows 10","client_id":1},
|
||||
{"id":3,"name":"IOS","client_id":2}]
|
||||
|
||||
However note that they will fail when trying to use :ref:`v_filter` and :ref:`h_filter` on them.
|
||||
|
||||
So while they can be used for quick tests, it's recommended to always choose a strict return type for the function.
|
||||
|
||||
Overloaded functions
|
||||
--------------------
|
||||
|
||||
You can call overloaded functions with different number of arguments.
|
||||
|
||||
.. code-block:: postgres
|
||||
|
||||
CREATE FUNCTION rental_duration(customer_id integer) ..
|
||||
|
||||
CREATE FUNCTION rental_duration(customer_id integer, from_date date) ..
|
||||
|
||||
.. tabs::
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
GET /rpc/rental_duration?customer_id=232 HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/rpc/rental_duration?customer_id=232"
|
||||
|
||||
.. tabs::
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
GET /rpc/rental_duration?customer_id=232&from_date=2018-07-01 HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/rpc/rental_duration?customer_id=232&from_date=2018-07-01"
|
||||
|
||||
.. important::
|
||||
|
||||
Overloaded functions with the same argument names but different types are not supported.
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
This page is a work in progress.
|
||||
|
||||
.. _url_grammar:
|
||||
|
||||
URL Grammar
|
||||
===========
|
||||
|
||||
@@ -10,7 +12,7 @@ URL Grammar
|
||||
Custom Queries
|
||||
--------------
|
||||
|
||||
The PostgREST URL grammar limits the kinds of queries clients can perform. It prevents arbitrary, potentially poorly constructed and slow client queries. It's good for quality of service, but means database administrators must create custom views and stored procedures to provide richer endpoints. The most common causes for custom endpoints are
|
||||
The PostgREST URL grammar limits the kinds of queries clients can perform. It prevents arbitrary, potentially poorly constructed and slow client queries. It's good for quality of service, but means database administrators must create custom views and functions to provide richer endpoints. The most common causes for custom endpoints are
|
||||
|
||||
* Table unions
|
||||
* More complicated joins than those provided by :ref:`resource_embedding`.
|
||||
@@ -29,15 +31,9 @@ To request this:
|
||||
|
||||
Do this:
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
GET /%D9%85%D9%88%D8%A7%D8%B1%D8%AF HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/%D9%85%D9%88%D8%A7%D8%B1%D8%AF"
|
||||
curl "http://localhost:3000/%D9%85%D9%88%D8%A7%D8%B1%D8%AF"
|
||||
|
||||
.. _tabs-cols-w-spaces:
|
||||
|
||||
@@ -46,15 +42,9 @@ Table / Columns with spaces
|
||||
|
||||
You can request table/columns with spaces in them by percent encoding the spaces with ``%20``:
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
GET /Order%20Items?Unit%20Price=lt.200 HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/Order%20Items?Unit%20Price=lt.200"
|
||||
curl "http://localhost:3000/Order%20Items?Unit%20Price=lt.200"
|
||||
|
||||
.. _reserved-chars:
|
||||
|
||||
@@ -65,44 +55,25 @@ If filters include PostgREST reserved characters(``,``, ``.``, ``:``, ``()``) yo
|
||||
|
||||
Here ``Hebdon,John`` and ``Williams,Mary`` are values.
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
GET /employees?name=in.(%22Hebdon,John%22,%22Williams,Mary%22) HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/employees?name=in.(%22Hebdon,John%22,%22Williams,Mary%22)"
|
||||
curl "http://localhost:3000/employees?name=in.(%22Hebdon,John%22,%22Williams,Mary%22)"
|
||||
|
||||
Here ``information.cpe`` is a column name.
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
GET /vulnerabilities?%22information.cpe%22=like.*MS* HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/vulnerabilities?%22information.cpe%22=like.*MS*"
|
||||
curl "http://localhost:3000/vulnerabilities?%22information.cpe%22=like.*MS*"
|
||||
|
||||
If the value filtered by the ``in`` operator has a double quote (``"``), you can escape it using a backslash ``"\""``. A backslash itself can be used with a double backslash ``"\\"``.
|
||||
|
||||
Here ``Quote:"`` and ``Backslash:\`` are percent-encoded values. Note that ``%5C`` is the percent-encoded backslash.
|
||||
|
||||
.. tabs::
|
||||
.. code-block:: bash
|
||||
|
||||
.. code-tab:: http
|
||||
|
||||
GET /marks?name=in.(%22Quote:%5C%22%22,%22Backslash:%5C%5C%22) HTTP/1.1
|
||||
|
||||
.. code-tab:: bash Curl
|
||||
|
||||
curl "http://localhost:3000/marks?name=in.(%22Quote:%5C%22%22,%22Backslash:%5C%5C%22)"
|
||||
curl "http://localhost:3000/marks?name=in.(%22Quote:%5C%22%22,%22Backslash:%5C%5C%22)"
|
||||
|
||||
.. note::
|
||||
|
||||
Some HTTP libraries might encode URLs automatically(e.g. :code:`axios`). In these cases you should use double quotes
|
||||
:code:`""` directly instead of :code:`%22`.
|
||||
|
||||
|
||||