]> gitweb.factorcode.org Git - factor.git/blob - unmaintained/db/mysql/lib/lib.factor
6c162488ed0e7083a5fd275ce0aa71aabbca0852
[factor.git] / unmaintained / db / mysql / lib / lib.factor
1 ! Copyright (C) 2007 Berlin Brown, 2008 Doug Coleman.
2 ! See http://factorcode.org/license.txt for license.
3 ! Adapted from mysql.h and mysql.c
4 ! Tested with MySQL version - 5.0.24a
5 USING: kernel alien io prettyprint sequences
6 namespaces arrays math db.mysql.ffi system accessors ;
7 IN: db.mysql.lib
8
9 SYMBOL: my-conn
10
11 TUPLE: mysql-db handle host user password db port ;
12 TUPLE: mysql-statement ;
13 TUPLE: mysql-result-set ;
14
15 : new-mysql ( -- conn )
16     f mysql_init ;
17
18 : mysql-error ( mysql -- )
19     [ mysql_error throw ] when* ;
20
21 ! : mysql-connect ( mysql-connection -- )
22     ! new-mysql over set-mysql-db-handle
23     ! dup {
24         ! mysql-db-handle
25         ! mysql-db-host
26         ! mysql-db-user
27         ! mysql-db-password
28         ! mysql-db-db
29         ! mysql-db-port
30     ! } get-slots f 0 mysql_real_connect mysql-error ;
31
32 ! =========================================================
33 ! Low level mysql utility definitions
34 ! =========================================================
35
36 : (mysql-query) ( mysql-connection query -- ret )
37     >r db-handle>> r> mysql_query ;
38
39 ! : (mysql-result) ( mysql-connection -- ret )
40     ! [ mysql-db-handle mysql_use_result ] keep 
41     ! [ set-mysql-connection-resulthandle ] keep ;
42
43 ! : (mysql-affected-rows) ( mysql-connection -- n )
44     ! mysql-connection-mysqlconn mysql_affected_rows ;
45
46 ! : (mysql-free-result) ( mysql-connection -- )
47     ! mysql-connection-resulthandle drop ;
48
49 ! : (mysql-row) ( mysql-connection -- row )
50     ! mysql-connection-resulthandle mysql_fetch_row ;
51
52 ! : (mysql-num-cols) ( mysql-connection -- n )
53     ! mysql-connection-resulthandle mysql_num_fields ;
54    
55 ! : mysql-char*-nth ( index object -- str )
56     ! ! Utility based on 'char*-nth' to perform an additional sanity check on the value
57     ! ! extracted from the array of strings.
58     ! void*-nth [ alien>char-string ] [ "" ] if* ;
59
60 ! : mysql-row>seq ( object n -- seq )
61     ! [ swap mysql-char*-nth ] map-with ;
62
63 ! : (mysql-result>seq) ( seq -- seq )
64     ! my-conn get (mysql-row) dup [       
65         ! my-conn get (mysql-num-cols) mysql-row>seq
66         ! over push
67         ! (mysql-result>seq)
68     ! ] [ drop ] if 
69     ! ! Perform needed cleanup on fetched results
70     ! my-conn get (mysql-free-result) ;
71
72 ! : mysql-query ( query -- ret )
73     ! >r my-conn get r> (mysql-query) drop
74     ! my-conn get (mysql-result) ;
75
76 ! : mysql-command ( query -- n )
77     ! mysql-query drop
78     ! my-conn get (mysql-affected-rows) ;