Amalegeni-Go
 

Example 1 : returning a primitive

A function returning a single value

(uses template se.tpl)

Let's start with a simple example: a function that returns an int. The question answered by this function is: "how many tables do I have in the database?".

1
2
3
4
5
6
func Count() int
<<  
    select count(1)
    from   pg_tables
    where  tableowner=user
>>  

You put this code in the file src/ex01/ex01.amg, and then run 'amgo' (the amalegeni-go executable) on it. This converts it into go-code. The full build instructions are further down this page.

The code calling your Count() function can look like the following:

1
2
3
4
5
6
7
func main() { 
    count, err:= ex01.Count()
    if err!=nil {
        fmt.Printf("Error: %v\n",err)
    }
    fmt.Printf("Count= %v\n\n",count)
}    

Line 2 is where the function gets called. After an error check is done on the following line, the result of the count is printed.

All the above code is pretty self-explanatory, ask for a more detailed explanation if it's unclear.

A function returning a slice

Let's move ahead, and look at a function that returns a number of rows, eg. a slice of strings.

1
2
3
4
5
func CountReturnsSlice() []string
<<  
    select distinct left(tablename,1)
    from  pg_tables
>>  

Again, it is called in a similar fashion:

1
2
3
4
5
6
7
8
9
func main() { 
    sl,err:=ex01.CountReturnsSlice()
    if err!=nil {
        fmt.Printf("Error: %v\n",err)
    }
    for _,el:= range (sl) {  
        fmt.Printf("%+v\n",el)
    }
}  

Instructions on how to build it

Prerequisites

  • you need to have Go installed
  • the postgresql database is used, so go get the 'github.com/lib/pq' driver
  • grab the 'amgo' version for your system: see amalegeni-go download

Instructions

Download and unpack the ex01.zip that contains the code for above examples, plus some boiler-plate code for connecting. When you open the 'ex01.amg' file, you'll notice it contains both the above examples.

First edit the 'setenv.sh' script, see instructions in the file on what to do. Then execute it, to set the PATH and GOPATH environment variables.

$ unzip ex01.zip 
$ cd plain 
$ vi setenv.sh 
$ . ./setenv.sh

Now run amgo (amalegeni-go) on the ex01.amg file:

$ amgo ex01.amg 
template/se.tpl * src/ex01/ex01.amg 
Generating: src/ex01/ex01_generated_func.go

Have a look at the generated file, the ..func.go file.

Then compile the code:

go install run/ex01

And run...

$ ex01

Count= 7

p
s
t
z
 
© Willem Moors, 2013 - 2020