plv8 是一個很強大的pg 擴展插件,咱們能夠直接額使用js 加強sql ,shortid 是一個用來生成短鏈接id 很方便的類庫
由於shortid 是一個npm 模塊,咱們須要使用一種方法使用require 的方式引用包,這個咱們能夠經過 plv8 node 模塊解決
如下是一個簡單的demonode
使用plv8 node 模塊主要是方便快速的生成plv8 pg 插件可以使用的npm 包(包含依賴的處理,基於browserify的處理)
原理實際上比較簡單,主要包含如下git
browserify +bable node api
ALTER DATABASE postgres SET "plv8.start_proc" TO "v8.plv8_init";
CREATE or replace FUNCTION shortid() RETURNS text AS
$$
const shortid = require('shortid');
const result = shortid.generate();
return result;
$$
LANGUAGE plv8;
{
"name": "node-plv8",
"version": "1.0.0",
"main": "app.js",
"bin": "app.js",
"license": "MIT",
"dependencies": {
"cuid": "^2.1.6",
"knex": "^0.20.1",
"lodash": "^4.17.15",
"pg": "^7.12.1",
"plv8": "^2.1.4",
"shortid": "^2.2.15",
"uuid": "^3.3.3"
},
"scripts": {
"init:app": "node app"
}
}
// setup plv8 connection
const PLV8 = require('plv8')
const knex = require('knex')
const knexHandle = knex({
client: 'pg',
connection: {
host: "127.0.0.1",
user: "postgres",
password: "dalong",
database: "postgres"
}
})
const plv8 = new PLV8(knexHandle)
// setup a log listener
plv8.on('log:error', msg => {
console.error(msg)
})
plv8.install({modulePath:require.resolve("shortid"),moduleName:"shortid"})
.then(() => {
// eval some code
return plv8.eval(() => {
const shortid = require('shortid')
return shortid.generate()
})
})
.then(result => {
console.log(result)
}).catch(err=>{
console.log(err)
})
爲了演示,模型比較簡單,主要是一個自增id 以及shortid 的存儲,shortid 的生成經過調用
咱們建立的函數shortidgithub
CREATE TABLE shortids (
id integer DEFAULT nextval('shorids_id_seq'::regclass) PRIMARY KEY,
shortid text
);
-- Indices -------------------------------------------------------
CREATE UNIQUE INDEX shorids_pkey ON shortids(id int4_ops);
insert into shortids(shortid) values(shortid());
從shortid 的算法上,隨機性比較高的,通常的猜想比較難,咱們經過plv8 以及強大的js能力,很方便的就能夠設計一個靈活的短鏈接服務算法
http://knexjs.org/#Installation-pooling
https://github.com/langateam/node-plv8
https://github.com/plv8/plv8
https://github.com/dylang/shortid
https://github.com/rongfengliang/plv8-require-learningsql