-
Notifications
You must be signed in to change notification settings - Fork 1
/
build_extension.nim
62 lines (43 loc) · 2.25 KB
/
build_extension.nim
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
from strutils import parseInt, repeat, join, split
from osproc import execCmd, execCmdEx
import tables,os
var nim_target_function* :string
{.push inline .}
proc compile_library(file:string) = discard execCmdEx "nim c -d:release --hints:off --opt:size --app:lib " & file & ".nim"
proc getLibName(file:string):string = "lib"&extractFilename(file)
proc getPostgresLibDir(): string = execCmdEx("pg_config --pkglibdir").output.split("\n")[0]
proc moveTo( libname:string, postgreslib:string ) = discard execCmd "sudo mv "&libname&".so "&postgreslib
proc extractV1Function( file:string ):string =
execCmdEx("""grep -i pgv1 """ & file & """.nim | awk '{ print $2}' | tr "()" "\n" | head -n1""").output.split("\n")[0]
proc createSQLFunction( file:string, nim_target_function: string): string =
var create_function = "CREATE OR REPLACE FUNCTION "&nim_target_function&"_template"
var types = {"Int16": "int", "Int32": "int", "Float4":"real", "Float8": "real", "Varchar": "varchar"}.toTable
var get_type:tuple[output:string, exitCode:int]
var return_type:tuple[output:string, exitCode:int]
var total_args:int
var param_builder:string = "("
var returns:string
var args:seq[string]
for key,value in types.pairs():
get_type = execCmdEx("grep -c get"&key&" "&file&".nim")
return_type = execCmdEx("grep -c return"&key&" "&file&".nim")
if get_type.exitCode == 0:
total_args = parseInt(get_type.output.split("\n")[0]) - 1
for i in 0..total_args:
args.add(value)
if return_type.exitCode == 0:
returns = " RETURNS "&value
param_builder = param_builder & args.join(",") & ")"
result = create_function & param_builder & returns & " as '"&getLibName(file)&".so' , '"&nim_target_function&"' LANGUAGE C STRICT;"
proc build_pg_function*( file:string ):string =
echo "Compiling: ",file, "..."
compile_library(file)
echo "Searching postgres libdir..."
var postgreslib = getPostgresLibDir()
var libname = getLibName(file)
echo "Moving ",libname,".so to ", postgreslib
libname.moveTo(postgreslib)
nim_target_function = extractV1Function(file)
echo "Creating SQL Function..."
result = createSQLFunction(file,nim_target_function)
{.pop.}