-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.html
1065 lines (995 loc) · 44.8 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!doctype html>
<html>
<head>
<title>PLV8 Documentation</title>
<link rel="stylesheet" href="css/site.css">
</head>
<body>
<div class="container">
<div class="one">
<h2>Contents</h2>
<div class="sidebar">
<ul>
<li><a href="#plv8" class="anchor">PLV8</li>
<ul>
<li><a href="#installing-plv8" class="anchor">Installing PLV8</li>
<ul>
<li><a href="#verifying-your-installation" class="anchor">Verifying Your Installation</li>
</ul>
<li><a href="#updating-plv8" class="anchor">Updating PLV8</li>
<ul>
<li><a href="#updating-older-plv8-installs" class="anchor">Updating Older PLV8 Installs</li>
</ul>
<li><a href="#runtime-environment-separation" class="anchor">Runtime Environment Separation</li>
<li><a href="#start-up-procedure" class="anchor">Start-up Procedure</li>
<li><a href="#stored-procedures" class="anchor">Stored procedures</li>
<ul>
<li><a href="#plv8_info" class="anchor">plv8_info</li>
<li><a href="#plv8_reset" class="anchor">plv8_reset</li>
</ul>
<li><a href="#building" class="anchor">Building</li>
<li><a href="#building-for-macos-linux" class="anchor">Building for MacOS/Linux</li>
<ul>
<li><a href="#linux" class="anchor">Linux</li>
<li><a href="#macos" class="anchor">MacOS</li>
<li><a href="#downloading-source" class="anchor">Downloading Source</li>
<li><a href="#building" class="anchor">Building</li>
<li><a href="#building-with-execution-timeout" class="anchor">Building with Execution Timeout</li>
<li><a href="#installing" class="anchor">Installing</li>
<li><a href="#testing" class="anchor">Testing</li>
</ul>
<li><a href="#runtime-configuration" class="anchor">Runtime Configuration</li>
</ul>
<li><a href="#function-calls" class="anchor">Function Calls</li>
<ul>
<li><a href="#scalar-function-calls" class="anchor">Scalar Function Calls</li>
<li><a href="#set-returning-function-calls" class="anchor">Set-returning Function Calls</li>
<li><a href="#trigger-function-calls" class="anchor">Trigger Function Calls</li>
<li><a href="#inline-statement-calls" class="anchor">Inline Statement Calls</li>
<li><a href="#auto-mapping-between-javascript-and-postgresql-built-in-types" class="anchor">Auto Mapping Between Javascript and PostgreSQL Built-in Types</li>
<li><a href="#typed-array" class="anchor">Typed Array</li>
</ul>
<li><a href="#plv8-built-ins" class="anchor">PLV8 Built-ins</li>
<ul>
<li><a href="#utility-functions" class="anchor">Utility Functions</li>
<ul>
<li><a href="#-code-plv8-elog-code-" class="anchor"><code>plv8.elog</code></li>
<li><a href="#-code-plv8-quote_literal-code-code-plv8-nullable-code-code-plv8-quote_ident-code-" class="anchor"><code>plv8.quote_literal</code>, <code>plv8.nullable</code>, <code>plv8.quote_ident</code></li>
<li><a href="#-code-plv8-find_function-code-" class="anchor"><code>plv8.find_function</code></li>
<li><a href="#-code-plv8-version-code-" class="anchor"><code>plv8.version</code></li>
<li><a href="#-code-plv8-memory_usage-code-" class="anchor"><code>plv8.memory_usage</code></li>
<li><a href="#-code-plv8-run_script-code-" class="anchor"><code>plv8.run_script</code></li>
</ul>
<li><a href="#database-access-via-spi" class="anchor">Database Access via SPI</li>
<ul>
<li><a href="#-code-plv8-execute-code-" class="anchor"><code>plv8.execute</code></li>
<li><a href="#-code-plv8-prepare-code-" class="anchor"><code>plv8.prepare</code></li>
<li><a href="#-code-preparedplan-execute-code-" class="anchor"><code>PreparedPlan.execute</code></li>
<li><a href="#-code-preparedplan-cursor-code-" class="anchor"><code>PreparedPlan.cursor</code></li>
<li><a href="#-code-preparedplan-free-code-" class="anchor"><code>PreparedPlan.free</code></li>
<li><a href="#-code-cursor-fetch-code-" class="anchor"><code>Cursor.fetch</code></li>
<li><a href="#-code-cursor-move-code-" class="anchor"><code>Cursor.move</code></li>
<li><a href="#-code-cursor-close-code-" class="anchor"><code>Cursor.close</code></li>
<li><a href="#-code-plv8-subtransaction-code-" class="anchor"><code>plv8.subtransaction</code></li>
</ul>
<li><a href="#window-function-api" class="anchor">Window Function API</li>
<ul>
<li><a href="#-code-windowobject-get_current_position-code-" class="anchor"><code>WindowObject.get_current_position</code></li>
<li><a href="#-code-windowobject-get_partition_row_count-code-" class="anchor"><code>WindowObject.get_partition_row_count</code></li>
<li><a href="#-code-windowobject-set_mark_position-code-" class="anchor"><code>WindowObject.set_mark_position</code></li>
<li><a href="#-code-windowobject-rows_are_peers-code-" class="anchor"><code>WindowObject.rows_are_peers</code></li>
<li><a href="#-code-windowobject-get_func_arg_in_partition-code-" class="anchor"><code>WindowObject.get_func_arg_in_partition</code></li>
<li><a href="#-code-windowobject-get_func_arg_in_frame-code-" class="anchor"><code>WindowObject.get_func_arg_in_frame</code></li>
<li><a href="#-code-windowobject-get_func_arg_in_current-code-" class="anchor"><code>WindowObject.get_func_arg_in_current</code></li>
<li><a href="#-code-windowobject-get_partition_local-code-" class="anchor"><code>WindowObject.get_partition_local</code></li>
<li><a href="#-code-windowobject-set_partition_local-code-" class="anchor"><code>WindowObject.set_partition_local</code></li>
</ul>
<li><a href="#external-utilities" class="anchor">External Utilities</li>
<li><a href="#plv8ify" class="anchor">PLV8ify</li>
<li><a href="#equinox" class="anchor">Equinox</li>
</div>
</div>
<div class="two-six">
<h1>
<a name="plv8" class="anchor" href="#plv8">
<span class="header-link"></span>
</a>
PLV8
</h1>
<p>PLV8 is a <em>trusted</em> Javascript language extension for PostgreSQL. It can be
used for <em>stored procedures</em>, <em>triggers</em>, etc.</p>
<p>PLV8 works with most versions of Postgres, version <code>13</code> and above.</p>
<h2>
<a name="installing-plv8" class="anchor" href="#installing-plv8">
<span class="header-link"></span>
</a>
Installing PLV8
</h2>
<p>If the PLV8 extension has been installed to your system, the PLV8 extension can
be installed into your PostgreSQL database by running:</p>
<pre><code>=# CREATE EXTENSION plv8;
</code></pre>
<h3>
<a name="verifying-your-installation" class="anchor" href="#verifying-your-installation">
<span class="header-link"></span>
</a>
Verifying Your Installation
</h3>
<p>You can verify the installation in two ways. As of PLV8 <code>2.0.0</code>, you can
execute a stored procedure:</p>
<pre><code>=# SELECT plv8_version();
</code></pre>
<p>Alternately, you can run the following on all versions of PLV8:</p>
<pre><code>=# DO $$ plv8.elog(NOTICE, plv8.version); $$ LANGUAGE plv8;
</code></pre>
<h2>
<a name="updating-plv8" class="anchor" href="#updating-plv8">
<span class="header-link"></span>
</a>
Updating PLV8
</h2>
<p>As of PLV8 version <code>2.3.3</code>, you can use upgrade scripts to upgrade your
installation from any version higher than <code>1.5.0</code>:</p>
<pre><code>=# ALTER EXTENSION plv8 UPDATE TO `3.2.0`;
</code></pre>
<p>Note that until the database has been restarted, the old version of PLV8 will
still be loaded, though <code>SELECT plv8_version()</code> will return the new version.
This is an artifact of how Postgres manages extensions.</p>
<h3>
<a name="updating-older-plv8-installs" class="anchor" href="#updating-older-plv8-installs">
<span class="header-link"></span>
</a>
Updating Older PLV8 Installs
</h3>
<p>Updating PL/v8 is usually straightforward as it is a small and stable extension</p>
<ul>
<li>it only contains a handful of objects that need to be added to PostgreSQL
when installing the extension.</li>
</ul>
<p>The procedure that is responsible for invoking this installation script
(generated during compile time based on plv8.sql.common), is controlled by
PostgreSQL and runs when CREATE EXTENSION is executed only. After building, it
takes the form of plv8--<version>.sql and is usually located under
<code>/usr/share/postgresql/<PG_MAJOR>/extension</code>, depending on the OS.</p>
<p>When this command is executed, PostgreSQL tracks which objects belong to the
extension and conversely removes them upon uninstallation, i.e., whenever
<code>DROP EXTENSION</code> is called.</p>
<p>You can explore some of the objects that PL/v8 stores under PostgreSQL:</p>
<pre><code>=# SELECT lanname FROM pg_catalog.pg_language WHERE lanname = 'plv8';
=# SELECT proname FROM pg_proc p WHERE p.proname LIKE 'plv8%';
=# SELECT typname FROM pg_catalog.pg_type WHERE typname LIKE 'plv8%';
</code></pre>
<p>To update PostgreSQL, you can <code>DROP</code> the existing extension:</p>
<pre><code>=# DROP EXTENSION plv8;
</code></pre>
<p>Install the new version, and <code>CREATE</code> the extension:</p>
<pre><code>=# CREATE EXTENSION plv8;
</code></pre>
<p>Alternately, you can backup and restore your database.</p>
<h2>
<a name="runtime-environment-separation" class="anchor" href="#runtime-environment-separation">
<span class="header-link"></span>
</a>
Runtime Environment Separation
</h2>
<p>In PLV8, each session has one global JS runtime context. This enables function
invocations at low cost, and sharing common object among the functions. However,
for the security reasons, if the user switches to another with SET ROLE command,
a new JS runtime context is initialized and used separately. This prevents the
risk of unexpected information leaking.</p>
<p>Each <code>plv8</code> function is invoked as if the function is the property of other
object. This means <code>this</code> in each function is a Javascript <code>object</code> that is created
every time the function is executed in a query. In other words, the life time and
the visibility of the <code>this</code> object in a function is only a series of function calls in
a query. If you need to share some value among different functions, keep it in the
global <code>plv8</code> object because each function invocation has a different <code>this</code> object.</p>
<h2>
<a name="start-up-procedure" class="anchor" href="#start-up-procedure">
<span class="header-link"></span>
</a>
Start-up Procedure
</h2>
<p>PLV8 provides a start up facility, which allows you to call a <code>plv8</code> runtime
environment initialization function specified in the GUC variable. This can
only be set by someone with administrator access to the database you are
accessing.</p>
<pre><code>SET plv8.start_proc = 'plv8_init';
SELECT plv8_test(10);
</code></pre>
<p>If this variable is set when the runtime is initialized, before the function
call of <code>plv8_test()</code> another <code>plv8</code> function <code>plv8_init()</code> is invoked. In such
initialization function, you can add any properties to <code>plv8</code> object to expose
common values or assign them to the this property. In the initialization function,
the receiver this is specially pointing to the global object, so the variables
that are assigned to the this property in this initialization are visible from
any subsequent function as global variables.</p>
<p>Remember <code>CREATE FUNCTION</code> also starts the <code>plv8</code> runtime environment, so make
sure to <code>SET</code> this GUC before any <code>plv8</code> actions including <code>CREATE FUNCTION</code>.</p>
<h2>
<a name="stored-procedures" class="anchor" href="#stored-procedures">
<span class="header-link"></span>
</a>
Stored procedures
</h2>
<p>There are a couple of utility procedures that will get installed.</p>
<p>These are useful for long-running connections from various backend services.</p>
<h3>
<a name="plv8_info" class="anchor" href="#plv8_info">
<span class="header-link"></span>
</a>
plv8_info
</h3>
<p>Get information about all the current running environments
on a specific connection from all users.</p>
<p>Can be run by superuser only.</p>
<pre><code class="language-sql">SELECT plv8_info();
</code></pre>
<p>Outputs JSON</p>
<pre><code class="language-json">[
{
"user": "user1",
"total_heap_size": 1327104,
"total_physical_size": 474336,
"used_heap_size": 386680,
"heap_size_limit": 270008320,
"external_memory": 0,
"number_of_native_contexts": 2,
"contexts": []
},
{
"user": "user2",
"total_heap_size": 1327104,
"total_physical_size": 474336,
"used_heap_size": 386680,
"heap_size_limit": 270008320,
"external_memory": 0,
"number_of_native_contexts": 3,
"contexts": ["my context"]
}
]
</code></pre>
<p><em>Note: "number_of_native_contexts" = "contexts".length + 2</em></p>
<h3>
<a name="plv8_reset" class="anchor" href="#plv8_reset">
<span class="header-link"></span>
</a>
plv8_reset
</h3>
<p>Reset user isolate or context</p>
<p>To reset a specific context run:</p>
<pre><code class="language-sql">SELECT plv8_reset('my context');
</code></pre>
<p>Will reset the context and re-create <code>globalThis</code> on a next invocation of that context.</p>
<p>To reset all contexts and reboot the whole environment of a specfifc user:</p>
<pre><code class="language-sql">SELECT plv8_reset();
</code></pre>
<p>Superusers can kill a specific user environment by impersonating the user:</p>
<pre><code class="language-sql">SET ROLE "some_user";
SELECT plv8_reset();
RESET ROLE;
</code></pre>
<h1>
<a name="building" class="anchor" href="#building">
<span class="header-link"></span>
</a>
Building
</h1>
<h2>
<a name="building-for-macos-linux" class="anchor" href="#building-for-macos-linux">
<span class="header-link"></span>
</a>
Building for MacOS/Linux
</h2>
<p>Building PLV8 for MacOS or Linux has some specific requirements:</p>
<h3>
<a name="linux" class="anchor" href="#linux">
<span class="header-link"></span>
</a>
Linux
</h3>
<p>The following packages must be installed to build on Ubuntu or Debian:</p>
<ul>
<li><code>libtinfo5</code></li>
<li><code>build-essential</code></li>
<li><code>pkg-config</code></li>
<li><code>libstdc++-12-dev</code> (depending on version, may be 10 instead of 12)</li>
<li><code>cmake</code></li>
<li><code>git</code></li>
</ul>
<p>The following packages must be installed to build on EL9 or EL8:</p>
<ul>
<li>'development tools' - via groupinstall</li>
<li><code>cmake</code></li>
<li><code>git</code></li>
</ul>
<p>Note that some distributions of Linux may have additional requirements. This
is not meant to be an exhaustive list.</p>
<h3>
<a name="macos" class="anchor" href="#macos">
<span class="header-link"></span>
</a>
MacOS
</h3>
<p>The following packages must be install to build on MacOS:</p>
<ul>
<li><code>XCode</code> - and the command line tools</li>
<li><code>cmake</code></li>
</ul>
<h3>
<a name="downloading-source" class="anchor" href="#downloading-source">
<span class="header-link"></span>
</a>
Downloading Source
</h3>
<p>Downloading the source code is very straightforward:</p>
<pre><code>$ git clone https://github.com/plv8/plv8
$ cd plv8
$ make
</code></pre>
<h3>
<a name="building" class="anchor" href="#building">
<span class="header-link"></span>
</a>
Building
</h3>
<p>Building is simple:</p>
<pre><code>$ make
</code></pre>
<p>This will download <code>v8</code> and compile it as well.</p>
<p>| Note: If you have multiple versions of PostgreSQL installed like 9.5 and 9.6, Plv8 will only be built for PostgreSQL 9.6. This is because make calls pg_config to get the version number, which will always be the latest version installed. If you need to build Plv8 for PostgreSQL 9.5 while you have 9.6 installed pass make the PG_CONFIG variable to your 9.5 version of pg_config. This works for <code>make</code>, and <code>make install</code>. For example in Ubuntu:</p>
<pre><code>$ make PG_CONFIG=/usr/lib/postgresql/13/bin/pg_config
</code></pre>
<h3>
<a name="building-with-execution-timeout" class="anchor" href="#building-with-execution-timeout">
<span class="header-link"></span>
</a>
Building with Execution Timeout
</h3>
<p>Plv8 allows you to optionally build with an execution timeout for Javascript
functions, when enabled at compile-time.</p>
<pre><code>$ make EXECUTION_TIMEOUT=1
</code></pre>
<p>By default, the execution timeout is not compiled, but when configured it has a
timeout of 300 seconds (5 minutes). You can override this by setting the
<code>plv8.execution_timeout</code> variable. It can be set between <code>1</code> second and <code>65536</code>
seconds, but cannot be disabled.</p>
<h3>
<a name="installing" class="anchor" href="#installing">
<span class="header-link"></span>
</a>
Installing
</h3>
<p>Once PLV8 has been built, you need to install it for PostgreSQL to be able to use
it:</p>
<pre><code>$ make install
</code></pre>
<p>This might require <code>root</code> access, depending on how PostgreSQL is installed:</p>
<pre><code>$ sudo make install
</code></pre>
<h3>
<a name="testing" class="anchor" href="#testing">
<span class="header-link"></span>
</a>
Testing
</h3>
<p>Once PLV8 is installed, you can verify the install by running:</p>
<pre><code>$ make installcheck
</code></pre>
<h1>
<a name="runtime-configuration" class="anchor" href="#runtime-configuration">
<span class="header-link"></span>
</a>
Runtime Configuration
</h1>
<p>PLV8 has some configuration variables that can be set either in <code>postgresql.conf</code>
or at runtime using <code>SET</code>.</p>
<table>
<thead>
<tr>
<th>Variable</th>
<th>Description</th>
<th>Default</th>
</tr>
</thead>
<tbody><tr>
<td><code>plv8.start_proc</code></td>
<td>PLV8 function to run once when PLV8 is first used</td>
<td><em>none</em></td>
</tr>
<tr>
<td><code>plv8.icu_data</code></td>
<td>ICU data file directory (when compiled with ICU support)</td>
<td><em>none</em></td>
</tr>
<tr>
<td><code>plv8.v8_flags</code></td>
<td>V8 engine initialization flags (e.g. --harmony for all current harmony features)</td>
<td><em>none</em></td>
</tr>
<tr>
<td><code>plv8.execution_timeout</code></td>
<td>V8 execution timeout (when compiled with EXECUTION_TIMEOUT)</td>
<td>300 seconds</td>
</tr>
<tr>
<td><code>plv8.boot_proc</code></td>
<td>Like <code>start_proc</code> above, but can be set by superuser only</td>
<td><em>none</em></td>
</tr>
<tr>
<td><code>plv8.memory_limit</code></td>
<td>Memory limit for the per-user heap usage on each connection, in <strong>MB</strong></td>
<td>256</td>
</tr>
<tr>
<td><code>plv8.context</code></td>
<td>Users can switch to a different global object (<code>globalThis</code>) by using an arbitrary context string</td>
<td><em>none</em></td>
</tr>
<tr>
<td><code>plv8.context_cache_size</code></td>
<td>Size of the per-user LRU cache for custom contexts</td>
<td>8</td>
</tr>
<tr>
<td><code>plv8.max_eval_size</code></td>
<td>Control how <code>eval()</code> can be used, -1 = no limits, 0 = <code>eval()</code> disabled, any other number = max length of the eval-able string in <strong>bytes</strong></td>
<td>2MB</td>
</tr>
</tbody></table>
<h1>
<a name="function-calls" class="anchor" href="#function-calls">
<span class="header-link"></span>
</a>
Function Calls
</h1>
<p>PLV8 has the ability to execute multiple types of function calls inside of
PostgreSQL.</p>
<h2>
<a name="scalar-function-calls" class="anchor" href="#scalar-function-calls">
<span class="header-link"></span>
</a>
Scalar Function Calls
</h2>
<p>In PLV8, you can write your invoked function call in Javascript, using the usual
<code>CREATE FUNCTION</code> statement. Here is an example of a <code>scalar</code> function call:</p>
<pre><code>CREATE FUNCTION plv8_test(keys TEXT[], vals TEXT[]) RETURNS JSON AS $$
var o = {};
for(var i=0; i<keys.length; i++){
o[keys[i]] = vals[i];
}
return o;
$$ LANGUAGE plv8 IMMUTABLE STRICT;
=# SELECT plv8_test(ARRAY['name', 'age'], ARRAY['Tom', '29']);
plv8_test
---------------------------
{"name":"Tom","age":"29"}
(1 row)
</code></pre>
<p>Internally, the function will defined such as:</p>
<pre><code>(function(keys, vals) {
var o = {};
for(var i=0; i<keys.length; i++){
o[keys[i]] = vals[i];
}
return o;
})
</code></pre>
<p>Where <code>keys</code> and <code>vals</code> are type checked and validated inside of PostgreSQL,
called as arguments to the function, and <code>o</code> is the object that is returned as
the <code>JSON</code> type back to PostgreSQL. If argument names are omitted in the creation
of the function, they will be available in the function as <code>$1</code>, <code>$2</code>, etc.</p>
<h2>
<a name="set-returning-function-calls" class="anchor" href="#set-returning-function-calls">
<span class="header-link"></span>
</a>
Set-returning Function Calls
</h2>
<p>PLV8 supports returning <code>SET</code> from function calls:</p>
<pre><code>CREATE TYPE rec AS (i integer, t text);
CREATE FUNCTION set_of_records() RETURNS SETOF rec AS
$$
// plv8.return_next() stores records in an internal tuplestore,
// and return all of them at the end of function.
plv8.return_next( { "i": 1, "t": "a" } );
plv8.return_next( { "i": 2, "t": "b" } );
// You can also return records with an array of JSON.
return [ { "i": 3, "t": "c" }, { "i": 4, "t": "d" } ];
$$
LANGUAGE plv8;
</code></pre>
<p>Running this gives you a <code>SETOF</code> result:</p>
<pre><code>=# SELECT * FROM set_of_records();
i | t
---+---
1 | a
2 | b
3 | c
4 | d
(4 rows)
</code></pre>
<p>Internally, if the function is declared as <code>RETURNS SETOF</code>, PLV8 prepares a
<code>tuplestore</code> every time every time it is called. You can call the
<code>plv8.return_next()</code> function as many times as you need to return a row. In
addition, you can also return an <code>array</code> to add a set of records.</p>
<p>If the argument object to <code>return_next()</code> has extra properties that are not
defined by the argument, <code>return_next()</code> raises an error.</p>
<h2>
<a name="trigger-function-calls" class="anchor" href="#trigger-function-calls">
<span class="header-link"></span>
</a>
Trigger Function Calls
</h2>
<p>PLV8 supports trigger function calls:</p>
<pre><code>CREATE FUNCTION test_trigger() RETURNS TRIGGER AS
$$
plv8.elog(NOTICE, "NEW = ", JSON.stringify(NEW));
plv8.elog(NOTICE, "OLD = ", JSON.stringify(OLD));
plv8.elog(NOTICE, "TG_OP = ", TG_OP);
plv8.elog(NOTICE, "TG_ARGV = ", TG_ARGV);
if (TG_OP == "UPDATE") {
NEW.i = 102;
return NEW;
}
$$
LANGUAGE "plv8";
CREATE TRIGGER test_trigger
BEFORE INSERT OR UPDATE OR DELETE
ON test_tbl FOR EACH ROW
EXECUTE PROCEDURE test_trigger('foo', 'bar');
</code></pre>
<p>If the trigger type is an <code>INSERT</code> or <code>UPDATE</code>, you can assign properties of
<code>NEW</code> variable to change the actual tuple stored by this operation. A PLV8
trigger function will have the following special arguments that contain the
trigger state:</p>
<ul>
<li><code>NEW</code></li>
<li><code>OLD</code></li>
<li><code>TG_NAME</code></li>
<li><code>TG_WHEN</code></li>
<li><code>TG_LEVEL</code></li>
<li><code>TG_OP</code></li>
<li><code>TG_RELID</code></li>
<li><code>TG_TABLE_NAME</code></li>
<li><code>TG_TABLE_SCHEMA</code></li>
<li><code>TG_ARGV</code></li>
</ul>
<p>For more information see the <a href="https://www.postgresql.org/docs/current/static/plpgsql-trigger.html">trigger section in PostgreSQL manual</a>.</p>
<h2>
<a name="inline-statement-calls" class="anchor" href="#inline-statement-calls">
<span class="header-link"></span>
</a>
Inline Statement Calls
</h2>
<p>PLV8 supports the <code>DO</code> block when using PostgreSQL 9.0 and above:</p>
<pre><code>DO $$ plv8.elog(NOTICE, 'this', 'is', 'inline', 'code'); $$ LANGUAGE plv8;
</code></pre>
<h2>
<a name="auto-mapping-between-javascript-and-postgresql-built-in-types" class="anchor" href="#auto-mapping-between-javascript-and-postgresql-built-in-types">
<span class="header-link"></span>
</a>
Auto Mapping Between Javascript and PostgreSQL Built-in Types
</h2>
<p>For the result and arguments, PostgreSQL types and Javascript types are mapped
automatically, if the desired PostgreSQL type is one of:</p>
<ul>
<li><code>OID</code></li>
<li><code>bool</code></li>
<li><code>INT3 </code></li>
<li><code>INT4</code></li>
<li><code>INT8</code></li>
<li><code>FLOAT4</code></li>
<li><code>FLOAT8</code></li>
<li><code>NUMERIC</code></li>
<li><code>DATE</code></li>
<li><code>TIMESTAMP</code></li>
<li><code>TIMESTAMPTZ</code></li>
<li><code>BYTEA</code></li>
<li><code>JSON</code> (>= 9.2)</li>
<li><code>JSONB</code> (>= 9.4)</li>
</ul>
<p>and the Javascript value looks compatible, then the conversion succeeds.
Otherwise, PLV8 tries to convert them via the <code>cstring</code> representation. An
<code>array</code> type is supported only if the dimension is one. A Javascript <code>object</code>
will be mapped to a <code>tuple</code> when applicable. In addition to these types, PLV8
supports polymorphic types such like <code>ANYELEMENT</code> and <code>ANYARRAY</code>. Conversion of
<code>BYTEA</code> is a little different story. See the <a href="#Typed%20Array">TypedArray section</a>.</p>
<h2>
<a name="typed-array" class="anchor" href="#typed-array">
<span class="header-link"></span>
</a>
Typed Array
</h2>
<p>The <code>typed array</code> is something <code>v8</code> provides to allow fast access to native
memory, mainly for the purpose of their canvas support in browsers. PLV8 uses
this to map <code>BYTEA</code> and various array types to a Javascript <code>array</code>. In the case
of <code>BYTEA</code>, you can access each byte as an array of unsigned bytes. For
<code>int2</code>/<code>int4</code>/<code>float4</code>/<code>float8</code> array types, PLV8 provides direct access to each
element by using PLV8 domain types.</p>
<ul>
<li><code>plv8_int2array</code> maps <code>int2[]</code></li>
<li><code>plv8_int4array</code> maps <code>int4[]</code></li>
<li><code>plv8_float4array</code> maps <code>float4[]</code></li>
<li><code>plv8_float8array</code> maps <code>float8[]</code></li>
</ul>
<p>These are only annotations that tell PLV8 to use the fast access method instead
of the regular one. For these typed arrays, only 1-dimensional arrays without
any <code>NULL</code> elements. There is currently no way to create such typed array inside
PLV8 functions, only arguments can be typed array. You can modify the element and
return the value. An example for these types are as follows:</p>
<pre><code>CREATE FUNCTION int4sum(ary plv8_int4array) RETURNS int8 AS $$
var sum = 0;
for (var i = 0; i < ary.length; i++) {
sum += ary[i];
}
return sum;
$$ LANGUAGE plv8 IMMUTABLE STRICT;
SELECT int4sum(ARRAY[1, 2, 3, 4, 5]);
int4sum
---------
15
(1 row)
</code></pre>
<h1>
<a name="plv8-built-ins" class="anchor" href="#plv8-built-ins">
<span class="header-link"></span>
</a>
PLV8 Built-ins
</h1>
<p>PLV8 includes a number of built-in functions bound to the <code>plv8</code> object for you
to use.</p>
<h2>
<a name="utility-functions" class="anchor" href="#utility-functions">
<span class="header-link"></span>
</a>
Utility Functions
</h2>
<h3>
<a name="-code-plv8-elog-code-" class="anchor" href="#-code-plv8-elog-code-">
<span class="header-link"></span>
</a>
<code>plv8.elog</code>
</h3>
<p><code>plv8.elog</code> emits a message to the client or the PostgreSQL log file. The
emit level is one of:</p>
<ul>
<li><code>DEBUG5</code></li>
<li><code>DEBUG4</code></li>
<li><code>DEBUG3</code></li>
<li><code>DEBUG2</code></li>
<li><code>DEBUG1</code></li>
<li><code>LOG</code></li>
<li><code>INFO</code></li>
<li><code>NOTICE</code></li>
<li><code>WARNING</code></li>
<li><code>ERROR</code></li>
</ul>
<pre><code>var msg = 'world';
plv8.elog(DEBUG1, 'Hello', `${msg}!`);
</code></pre>
<p>See the <a href="https://www.postgresql.org/docs/current/static/runtime-config-logging.html#RUNTIME-CONFIG-SEVERITY-LEVELS">PostgreSQL manual</a> for information on each error level.</p>
<h3>
<a name="-code-plv8-quote_literal-code-code-plv8-nullable-code-code-plv8-quote_ident-code-" class="anchor" href="#-code-plv8-quote_literal-code-code-plv8-nullable-code-code-plv8-quote_ident-code-">
<span class="header-link"></span>
</a>
<code>plv8.quote_literal</code>, <code>plv8.nullable</code>, <code>plv8.quote_ident</code>
</h3>
<p>Each function for the quote family is identical to the built-in SQL function
with the same name.</p>
<h3>
<a name="-code-plv8-find_function-code-" class="anchor" href="#-code-plv8-find_function-code-">
<span class="header-link"></span>
</a>
<code>plv8.find_function</code>
</h3>
<p>PLV8 provides a function to access other functions defined as <code>plv8</code> functions
that have been registered in the database.</p>
<pre><code>CREATE FUNCTION callee(a int) RETURNS int AS $$ return a * a $$ LANGUAGE plv8;
CREATE FUNCTION caller(a int, t int) RETURNS int AS $$
var func = plv8.find_function("callee");
return func(a);
$$ LANGUAGE plv8;
</code></pre>
<p>With <code>plv8.find_function()</code>, you can look up other PLV8 functions. If they
are not a PLV8 function, and error is thrown. The function signature parameter
to <code>plv8.find_function()</code> is either of <code>regproc</code> (function name only) or
<code>regprocedure</code> (function name with argument types). You can make use of the
internal type for arguments and void type for return type for the pure Javascript
function to make sure any invocation from SQL statements should not occur.</p>
<h3>
<a name="-code-plv8-version-code-" class="anchor" href="#-code-plv8-version-code-">
<span class="header-link"></span>
</a>
<code>plv8.version</code>
</h3>
<p>The <code>plv8</code> object provides a version string as <code>plv8.version</code>. This string
corresponds to the <code>plv8</code> module version.</p>
<h3>
<a name="-code-plv8-memory_usage-code-" class="anchor" href="#-code-plv8-memory_usage-code-">
<span class="header-link"></span>
</a>
<code>plv8.memory_usage</code>
</h3>
<p>You can get your own memory usage by calling <code>plv8.memory_usage()</code> with no params.
The resulting object looks like this:</p>
<pre><code class="language-json">{
"total_heap_size":1327104,
"total_physical_size":472712,
"used_heap_size":381748,
"heap_size_limit":270008320,
"external_memory":0,
"number_of_native_contexts":2
}
</code></pre>
<p>See nodejs <a href="https://nodejs.org/api/v8.html#v8_v8_getheapstatistics">v8.getHeapStatistics()</a></p>
<h3>
<a name="-code-plv8-run_script-code-" class="anchor" href="#-code-plv8-run_script-code-">
<span class="header-link"></span>
</a>
<code>plv8.run_script</code>
</h3>
<p>Run a script from source code, it's like <code>eval()</code> but takes a second argument: script name<br>Can be pretty useful for debugging</p>
<p>Can be used like this</p>
<pre><code class="language-js">const sourceCode = `globalThis.myFunc = () => 42`
try {
plv8.run_script(sourceCode, 'myScript.js')
myFunc()
} catch (e) {
plv8.elog(NOTICE, e.message)
}
</code></pre>
<h2>
<a name="database-access-via-spi" class="anchor" href="#database-access-via-spi">
<span class="header-link"></span>
</a>
Database Access via SPI
</h2>
<p>PLV8 provides functions for database access, including prepared statements,
and cursors.</p>
<h3>
<a name="-code-plv8-execute-code-" class="anchor" href="#-code-plv8-execute-code-">
<span class="header-link"></span>
</a>
<code>plv8.execute</code>
</h3>
<p><code>plv8.execute(sql [, args])</code></p>
<p>Executes SQL statements and retrieves the results. The <code>sql</code> argument is
required, and the <code>args</code> argument is an optional <code>array</code> containing any arguments
passed in the SQL query. For <code>SELECT</code> queries, the returned value is an <code>array</code>
of <code>objects</code>. Each <code>object</code> represents one row, with the <code>object</code> properties
mapped as column names. For non-<code>SELECT</code> queries, the return result is the
number of rows affected.</p>
<pre><code>var json_result = plv8.execute('SELECT * FROM tbl');
var num_affected = plv8.execute('DELETE FROM tbl WHERE price > $1', [ 1000 ]);
</code></pre>
<h3>
<a name="-code-plv8-prepare-code-" class="anchor" href="#-code-plv8-prepare-code-">
<span class="header-link"></span>
</a>
<code>plv8.prepare</code>
</h3>
<p><code>plv8.prepare(sql [, typenames])</code></p>
<p>Opens or creates a prepared statement. The <code>typename</code> parameter is an <code>array</code>
where each element is a <code>string</code> that corresponds to the PostgreSQL type name
for each <code>bind</code> parameter. Returned value is an object of the <code>PreparedPlan</code> type.
This object must be freed by <code>plan.free()</code> before leaving the function.</p>
<pre><code>var plan = plv8.prepare('SELECT * FROM tbl WHERE col = $1', [ 'int' ]);
var rows = plan.execute([ 1 ]);
var sum = 0;
for (var i = 0; i < rows.length; i++) {
sum += rows[i].num;
}
plan.free();
return sum;
</code></pre>
<h3>
<a name="-code-preparedplan-execute-code-" class="anchor" href="#-code-preparedplan-execute-code-">
<span class="header-link"></span>
</a>
<code>PreparedPlan.execute</code>
</h3>
<p><code>PreparedPlan.execute([ args ])</code></p>
<p>Executes the prepared statement. The <code>args</code> parameter is the same as what would be
required for <code>plv8.execute()</code>, and can be omitted if the statement does not have
any parameters. The result of this method is also the same as <code>plv8.execute()</code>.</p>
<h3>
<a name="-code-preparedplan-cursor-code-" class="anchor" href="#-code-preparedplan-cursor-code-">
<span class="header-link"></span>
</a>
<code>PreparedPlan.cursor</code>
</h3>
<p><code>PreparedPlan.cursor([ args ])</code></p>
<p>Opens a cursor form the prepared statement. The <code>args</code> parameter is the same as
what would be required for <code>plv8.execute()</code> and <code>PreparedPlan.execute()</code>. The
returned object is of type <code>Cursor</code>. This must be closed by <code>Cursor.close()</code>
before leaving the function.</p>
<pre><code>var plan = plv8.prepare('SELECT * FROM tbl WHERE col = $1', [ 'int' ]);
var cursor = plan.cursor([ 1 ]);
var sum = 0, row;
while (row = cursor.fetch()) {
sum += row.num;
}
cursor.close();
plan.free();
return sum;
</code></pre>
<h3>
<a name="-code-preparedplan-free-code-" class="anchor" href="#-code-preparedplan-free-code-">
<span class="header-link"></span>
</a>
<code>PreparedPlan.free</code>
</h3>
<p>Frees the prepared statement.</p>
<h3>
<a name="-code-cursor-fetch-code-" class="anchor" href="#-code-cursor-fetch-code-">
<span class="header-link"></span>
</a>
<code>Cursor.fetch</code>
</h3>
<p><code>Cursor.fetch([ nrows ])</code></p>
<p>When the <code>nrows</code> parameter is omitted, fetches a row from the cursor and returns
it as an <code>object</code> (note: not as an <code>array</code>). If specified, fetches as many rows
as the <code>nrows</code> parameter, up to the number of rows available, and returns an
<code>array</code> of <code>objects</code>. A negative value will fetch backward.</p>
<h3>
<a name="-code-cursor-move-code-" class="anchor" href="#-code-cursor-move-code-">
<span class="header-link"></span>
</a>
<code>Cursor.move</code>
</h3>
<p><code>Cursor.move(nrows)</code></p>
<p>Moves the cursor <code>nrows</code>. A negative value will move backward.</p>
<h3>
<a name="-code-cursor-close-code-" class="anchor" href="#-code-cursor-close-code-">
<span class="header-link"></span>
</a>
<code>Cursor.close</code>
</h3>
<p>Closes the <code>Cursor</code>.</p>
<h3>
<a name="-code-plv8-subtransaction-code-" class="anchor" href="#-code-plv8-subtransaction-code-">
<span class="header-link"></span>
</a>
<code>plv8.subtransaction</code>
</h3>
<p><code>plv8.subtransaction(func)</code></p>
<p><code>plv8.execute()</code> creates a subtransaction each time it executes. If you need
an atomic operation, you will need to call <code>plv8.subtransaction()</code> to create
a subtransaction block.</p>
<pre><code>try{
plv8.subtransaction(function(){
plv8.execute("INSERT INTO tbl VALUES(1)"); // should be rolled back!
plv8.execute("INSERT INTO tbl VALUES(1/0)"); // occurs an exception
});
} catch(e) {
... execute fall back plan ...
}
</code></pre>
<p>If one of the SQL execution in the subtransaction block fails, all of operations
within the block are rolled back. If the process in the block throws a Javascript
exception, it is carried forward. So use a <code>try ... catch</code> block to capture it and
do alternative operations if it occurs.</p>
<h2>
<a name="window-function-api" class="anchor" href="#window-function-api">
<span class="header-link"></span>
</a>
Window Function API
</h2>
<p>You can define user-defined window functions with PLV8. It wraps the C-level
window function API to support full functionality. To create one, first obtain a
window object by calling <code>plv8.get_window_object()</code>, which provides the following
interfaces:</p>
<h3>
<a name="-code-windowobject-get_current_position-code-" class="anchor" href="#-code-windowobject-get_current_position-code-">
<span class="header-link"></span>
</a>
<code>WindowObject.get_current_position</code>
</h3>
<p>Returns the current position in the partition, starting from <code>0</code>.</p>
<h3>
<a name="-code-windowobject-get_partition_row_count-code-" class="anchor" href="#-code-windowobject-get_partition_row_count-code-">
<span class="header-link"></span>
</a>
<code>WindowObject.get_partition_row_count</code>
</h3>
<p>Returns the number of rows in the partition.</p>
<h3>
<a name="-code-windowobject-set_mark_position-code-" class="anchor" href="#-code-windowobject-set_mark_position-code-">
<span class="header-link"></span>
</a>
<code>WindowObject.set_mark_position</code>
</h3>
<p><code>WindowObject.set_mark_position(pos)</code></p>
<p>Sets the mark at the specified row. Rows above this position will be gone and
no longer accessible later.</p>
<h3>
<a name="-code-windowobject-rows_are_peers-code-" class="anchor" href="#-code-windowobject-rows_are_peers-code-">
<span class="header-link"></span>
</a>
<code>WindowObject.rows_are_peers</code>
</h3>
<p><code>WindowObject.rows_are_peers(pos1, pos1)</code></p>
<p>Returns <code>true</code> if the rows at <code>pos1</code> and <code>pos2</code> are peers.</p>
<h3>
<a name="-code-windowobject-get_func_arg_in_partition-code-" class="anchor" href="#-code-windowobject-get_func_arg_in_partition-code-">
<span class="header-link"></span>
</a>
<code>WindowObject.get_func_arg_in_partition</code>
</h3>
<p><code>WindowObject.get_func_arg_in_partition(argno, relpos, seektype, mark_pos)</code></p>
<h3>
<a name="-code-windowobject-get_func_arg_in_frame-code-" class="anchor" href="#-code-windowobject-get_func_arg_in_frame-code-">
<span class="header-link"></span>
</a>
<code>WindowObject.get_func_arg_in_frame</code>
</h3>
<p><code>WindowObject.get_func_arg_in_frame(argno, relpos, seektype, mark_pos)</code></p>
<p>Returns the value of the argument in <code>argno</code> (starting from 0) to this function
at the <code>relpos</code> row from <code>seektype</code> in the current partition or frame.
<code>seektype</code> can be either of <code>WindowObject.SEEK_HEAD</code>, <code>WindowObject.SEEK_CURRENT</code>,
or <code>WindowObject.SEEK_TAIL</code>. If <code>mark_pos</code> is <code>true</code>, the row the argument is
fetched from is marked. If the specified row is out of the partition/frame, the
returned value will be undefined.</p>
<h3>
<a name="-code-windowobject-get_func_arg_in_current-code-" class="anchor" href="#-code-windowobject-get_func_arg_in_current-code-">
<span class="header-link"></span>
</a>