Database Reference
In-Depth Information
Node.js users, and other users who want to use Javascript for building network
applications, will appreciate that PL/V8 and Node.js are built on the same Google
V8 engine and that many of the libraries available for Node.js will work largely
unchanged when used in PL/V8. There is an extension called plv8x that makes
using Node.js modules and modules you build easier to reuse in PL/V8.
You can find several examples on our site of PL/V8 use, some even involving copying
fairly large bodies of JavaScript code that we pulled from the Web and wrapping them
in a PL/V8 wrapper, as detailed in Using PLV8 to build JSON Selectors . The PL/V8
family mates perfectly with web applications because much of the same client-side Java‐
Script logic can be reused. More important, it makes a great all-purpose language for
developing numeric functions, updating data, and so on.
Basic Functions
One of the great benefits of PL/V8 is that you can use any JavaScript function in your
PL/V8 functions with minimal change. For example, you'll find many JavaScript ex‐
amples on the Web to validate email address. We arbitrarily picked one and made a PL/
V8 out of it in Example 8-16 .
Example 8-16. Using PL/V8 to validate email address
CREATE OR REPLACE FUNCTION
validate_email ( email text ) returns boolean as
$$
var re = / \ S +@ \ S + \ . \ S +/ ;
return re . test ( email );
$$ LANGUAGE plv8 IMMUTABLE STRICT ;
Our code uses a JavaScript regex object to check the email address. To use the function,
see Example 8-17 .
Example 8-17. Calling PL/V8 email validator
SELECT email , validate_email ( email ) AS is_valid
FROM ( VALUES ( 'alexgomezq@gmail.com' )
,( 'alexgomezqgmail.com' ),( 'alexgomezq@gmailcom' )) AS x ( email );
which outputs:
email | is_valid
----------------------+----------
alexgomezq@gmail.com | t
alexgomezqgmail.com | f
alexgomezq@gmailcom | f
Although you can code the same function using the PL/pgSQL and PostgreSQL's own
regular expression support, we guiltlessly poached someone else's time-tested code and
wasted no time of our own. If you're a web developer and find yourself having to validate
Search WWH ::




Custom Search