1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

Revert "db: increase db module level in vlib "

This reverts commit cd6d175180.
This commit is contained in:
Alexander Medvednikov
2020-03-26 09:23:54 +01:00
parent cd6d175180
commit ec4be80bcc
17 changed files with 37 additions and 34 deletions

View File

@ -1,60 +0,0 @@
module mysql
struct C.MYSQL
struct C.MYSQL_RES
struct C.MYSQL_FIELD {
name byteptr /* Name of column */
org_name byteptr /* Original column name, if an alias */
table byteptr /* Table of column if column was a field */
org_table byteptr /* Org table name, if table was an alias */
db byteptr /* Database for table */
catalog byteptr /* Catalog for table */
def byteptr /* Default value (set by mysql_list_fields) */
length int /* Width of column (create length) */
max_length int /* Max width for selected set */
name_length u32
org_name_length u32
table_length u32
org_table_length u32
db_length u32
catalog_length u32
def_length u32
flags u32 /* Div flags */
decimals u32 /* Number of decimals in field */
charsetnr u32 /* Character set */
@type int /* Type of field. See mysql_com.h for types */
}
fn C.mysql_init(mysql &MYSQL) &MYSQL
fn C.mysql_real_connect(mysql &MYSQL, host byteptr, user byteptr, passwd byteptr, db byteptr, port u32, unix_socket byteptr, clientflag u64) &MYSQL
fn C.mysql_query(mysql &MYSQL, q byteptr) int
fn C.mysql_select_db(mysql &MYSQL, db byteptr) int
fn C.mysql_change_user(mysql &MYSQL, user byteptr, password byteptr, db byteptr) bool
fn C.mysql_affected_rows(mysql &MYSQL) u64
fn C.mysql_options(mysql &MYSQL, option int, arg voidptr) int
fn C.mysql_get_option(mysql &MYSQL, option int, arg voidptr) int
fn C.mysql_num_fields(res &MYSQL_RES) int
fn C.mysql_autocommit(mysql MYSQL, mode bool)
fn C.mysql_refresh(mysql MYSQL, options u32) int
fn C.mysql_reset_connection(mysql MYSQL) int
fn C.mysql_ping(mysql MYSQL) int
fn C.mysql_store_result(mysql &MYSQL) &MYSQL_RES
fn C.mysql_fetch_row(res &MYSQL_RES) &byteptr
fn C.mysql_fetch_fields(res &MYSQL_RES) &MYSQL_FIELD
fn C.mysql_free_result(res &MYSQL_RES)
fn C.mysql_real_escape_string_quote(mysql &MYSQL, to byteptr, from byteptr, len u64, quote byte) u64
fn C.mysql_close(sock &MYSQL)
/* INFO & VERSION */
fn C.mysql_info(mysql &MYSQL) byteptr
fn C.mysql_get_host_info(mysql &MYSQL) byteptr
fn C.mysql_get_server_info(mysql &MYSQL) byteptr
fn C.mysql_get_server_version(mysql &MYSQL) u64
fn C.mysql_get_client_version() u64
fn C.mysql_get_client_info() byteptr
/* DEBUG & ERROR INFO */
fn C.mysql_error(mysql &MYSQL) byteptr
fn C.mysql_errno(mysql &MYSQL) int
fn C.mysql_dump_debug_info(mysql &MYSQL) int
fn C.mysql_debug(debug byteptr)

View File

@ -1,31 +0,0 @@
module mysql
/* MYSQL CONNECT FLAGS */
pub const (
// CAN_HANDLE_EXPIRED_PASSWORDS = C.CAN_HANDLE_EXPIRED_PASSWORDS
CLIENT_COMPRESS = C.CLIENT_COMPRESS
CLIENT_FOUND_ROWS = C.CLIENT_FOUND_ROWS
CLIENT_IGNORE_SIGPIPE = C.CLIENT_IGNORE_SIGPIPE
CLIENT_IGNORE_SPACE = C.CLIENT_IGNORE_SPACE
CLIENT_INTERACTIVE = C.CLIENT_INTERACTIVE
CLIENT_LOCAL_FILES = C.CLIENT_LOCAL_FILES
CLIENT_MULTI_RESULTS = C.CLIENT_MULTI_RESULTS
CLIENT_MULTI_STATEMENTS = C.CLIENT_MULTI_STATEMENTS
CLIENT_NO_SCHEMA = C.CLIENT_NO_SCHEMA
CLIENT_ODBC = C.CLIENT_ODBC
// CLIENT_OPTIONAL_RESULTSET_METADATA = C.CLIENT_OPTIONAL_RESULTSET_METADATA
CLIENT_SSL = C.CLIENT_SSL
CLIENT_REMEMBER_OPTIONS = C.CLIENT_REMEMBER_OPTIONS
)
/* MYSQL REFRESH FLAGS */
pub const (
REFRESH_GRANT = u32(C.REFRESH_GRANT)
REFRESH_LOG = u32(C.REFRESH_LOG)
REFRESH_TABLES = u32(C.REFRESH_TABLES)
REFRESH_HOSTS = u32(C.REFRESH_HOSTS)
REFRESH_STATUS = u32(C.REFRESH_STATUS)
REFRESH_THREADS = u32(C.REFRESH_THREADS)
REFRESH_SLAVE = u32(C.REFRESH_SLAVE)
REFRESH_MASTER = u32(C.REFRESH_MASTER)
)

View File

@ -1,72 +0,0 @@
module mysql
pub enum FieldType {
type_decimal
type_tiny
type_short
type_long
type_float
type_double
type_null
type_timestamp
type_longlong
type_int24
type_date
type_time
type_datetime
type_year
type_newdate
type_varchar
type_bit
type_timestamp2
type_datetime2
type_time2
type_json = 245
type_newdecimal
type_enum
type_set
type_tiny_blob
type_medium_blob
type_long_blob
type_blob
type_var_string
type_string
type_geometry
}
pub fn (f FieldType) str() string {
return match f {
0 { 'decimal' }
1 { 'tiny' }
2 { 'short' }
3 { 'long' }
4 { 'float' }
5 { 'double' }
6 { 'null' }
7 { 'timestamp' }
8 { 'longlong' }
9 { 'int24' }
10 { 'date' }
11 { 'time' }
12 { 'datetime' }
13 { 'year' }
14 { 'newdate' }
15 { 'varchar' }
16 { 'bit' }
17 { 'timestamp2' }
18 { 'datetime2' }
19 { 'time2' }
245 { 'json' }
246 { 'newdecimal' }
247 { 'enum' }
248 { 'set' }
249 { 'tiny_blob' }
250 { 'medium_blob' }
251 { 'long_blob' }
252 { 'blob' }
253 { 'var_string' }
254 { 'string' }
255 { 'geometry' }
else { 'unknown' }
}
}

View File

@ -1,169 +0,0 @@
module mysql
#flag -lmysqlclient
#flag linux -I/usr/include/mysql
#include <mysql.h>
pub struct Connection {
host string
port u32
username string
password string
dbname string
flag int
mut:
conn &MYSQL
}
pub fn new_connection(host, username, password, dbname string) ?Connection {
instance := mysql_init(0)
if isnil(instance) {
return error_with_code(get_error_msg(instance), get_errno(instance))
}
return Connection{ host, 0, username, password, dbname, 0, instance }
}
pub fn (conn mut Connection) connect() ?bool {
mut instance := mysql_init(0)
if !isnil(conn.conn) {
instance = conn.conn
}
if isnil(instance) {
return error_with_code(get_error_msg(instance), get_errno(instance))
}
conn.conn = C.mysql_real_connect(
instance,
conn.host.str,
conn.username.str,
conn.password.str,
conn.dbname.str,
conn.port,
0,
conn.flag
)
if isnil(conn.conn) {
return error_with_code(get_error_msg(instance), get_errno(instance))
}
return true
}
pub fn (conn Connection) query(q string) ?Result {
if mysql_query(conn.conn, q.str) != 0 {
return error_with_code(get_error_msg(conn.conn), get_errno(conn.conn))
}
res := mysql_store_result(conn.conn)
return Result{res}
}
pub fn (conn Connection) select_db(dbname string) ?bool {
if mysql_select_db(conn.conn, dbname.str) != 0 {
return error_with_code(get_error_msg(conn.conn), get_errno(conn.conn))
}
return true
}
pub fn (conn Connection) change_user(username, password, dbname string) ?bool {
mut ret := true
if (dbname != '') {
ret = mysql_change_user(conn.conn, username.str, password.str, dbname.str)
} else {
ret = mysql_change_user(conn.conn, username.str, password.str, 0)
}
if !ret {
return error_with_code(get_error_msg(conn.conn), get_errno(conn.conn))
}
return ret
}
pub fn (conn Connection) affected_rows() u64 {
return mysql_affected_rows(conn.conn)
}
pub fn (conn Connection) autocommit(mode bool) {
mysql_autocommit(conn.conn, mode)
}
pub fn (conn Connection) escape_string(s string) string {
len := strlen(s.str)
to := malloc(2 * len + 1)
quote := byte(39) // single quote
mysql_real_escape_string_quote(conn.conn, to, s.str, len, quote)
return string(to)
}
pub fn (conn Connection) set_option(option_type int, val voidptr) {
mysql_options(conn.conn, option_type, val)
}
pub fn (conn Connection) get_option(option_type int) ?voidptr {
ret := voidptr(0)
if mysql_get_option(conn.conn, option_type, &ret) != 0 {
return error_with_code(get_error_msg(conn.conn), get_errno(conn.conn))
}
return ret
}
pub fn (conn Connection) refresh(options u32) ?bool {
if mysql_refresh(conn.conn, options) != 0 {
return error_with_code(get_error_msg(conn.conn), get_errno(conn.conn))
}
return true
}
pub fn (conn Connection) reset_connection() ?bool {
if mysql_reset_connection(conn.conn) != 0 {
return error_with_code(get_error_msg(conn.conn), get_errno(conn.conn))
}
return true
}
pub fn (conn Connection) ping() ?bool {
if mysql_ping(conn.conn) != 0 {
return error_with_code(get_error_msg(conn.conn), get_errno(conn.conn))
}
return true
}
pub fn (conn Connection) close() {
mysql_close(conn.conn)
}
/* MYSQL INFO & VERSION */
pub fn (conn Connection) info() string {
return string(mysql_info(conn.conn))
}
pub fn (conn Connection) get_host_info() string {
return string(mysql_get_host_info(conn.conn))
}
pub fn (conn Connection) get_server_info() string {
return string(mysql_get_server_info(conn.conn))
}
pub fn (conn Connection) get_server_version() u64 {
return mysql_get_server_version(conn.conn)
}
pub fn get_client_version() u64 {
return mysql_get_client_version()
}
pub fn get_client_info() string {
return string(mysql_get_client_info())
}
/* MYSQL DEBUG */
pub fn (conn Connection) dump_debug_info() ?bool {
if mysql_dump_debug_info(conn.conn) != 0 {
return error_with_code(get_error_msg(conn.conn), get_errno(conn.conn))
}
return true
}
pub fn debug(debug string) {
mysql_debug(debug.str)
}

View File

@ -1,120 +0,0 @@
module mysql
pub struct Result {
result &MYSQL_RES
}
pub struct Row {
pub mut:
vals []string
}
pub struct Field {
name string
org_name string
table string
org_table string
db string
catalog string
def string
length int
max_length int
name_length u32
org_name_length u32
table_length u32
org_table_length u32
db_length u32
catalog_length u32
def_length u32
flags u32
decimals u32
charsetnr u32
type_ FieldType
}
pub fn (r Result) fetch_row() &byteptr {
return mysql_fetch_row(r.result)
}
pub fn (r Result) num_fields() int {
return mysql_num_fields(r.result)
}
pub fn (r Result) rows() []Row {
mut rows := []Row
nr_cols := r.num_fields()
for rr := r.fetch_row(); rr; rr = r.fetch_row() {
mut row := Row{}
for i in 0..nr_cols {
if rr[i] == 0 {
row.vals << ''
} else {
row.vals << string(rr[i])
}
}
rows << row
}
return rows
}
pub fn (r Result) fetch_fields() []Field {
mut fields := []Field
nr_cols := r.num_fields()
orig_fields := mysql_fetch_fields(r.result)
for i in 0..nr_cols {
fields << Field{
name: string(orig_fields[i].name)
org_name: string(orig_fields[i].org_name)
table: string(orig_fields[i].table)
org_table: string(orig_fields[i].org_table)
db: string(orig_fields[i].db)
catalog: string(orig_fields[i].catalog)
def: resolve_nil_str(orig_fields[i].def)
length: orig_fields.length
max_length: orig_fields.max_length
name_length: orig_fields.name_length
org_name_length: orig_fields.org_name_length
table_length: orig_fields.table_length
org_table_length: orig_fields.org_table_length
db_length: orig_fields.db_length
catalog_length: orig_fields.catalog_length
def_length: orig_fields.def_length
flags: orig_fields.flags
decimals: orig_fields.decimals
charsetnr: orig_fields.charsetnr
type_: FieldType(orig_fields.@type)
}
}
return fields
}
pub fn (f Field) str() string {
return '
{
name: "$f.name"
org_name: "$f.org_name"
table: "$f.table"
org_table: "$f.org_table"
db: "$f.db"
catalog: "$f.catalog"
def: "$f.def"
length: $f.length
max_length: $f.max_length
name_length: $f.name_length
org_name_length: $f.org_name_length
table_length: $f.table_length
org_table_length: $f.org_table_length
db_length: $f.db_length
catalog_length: $f.catalog_length
def_length: $f.def_length
flags: $f.flags
decimals: $f.decimals
charsetnr: $f.charsetnr
type: ${f.type_.str()}
}
'
}
pub fn (r Result) free() {
mysql_free_result(r.result)
}

View File

@ -1,16 +0,0 @@
module mysql
fn get_error_msg(conn &MYSQL) string {
return string(mysql_error(conn))
}
fn get_errno(conn &MYSQL) int {
return mysql_errno(conn)
}
fn resolve_nil_str(ptr byteptr) string {
if isnil(ptr) {
return ''
}
return string(ptr)
}

View File

@ -1,55 +0,0 @@
//import pg
struct Modules {
id int
user_id int
name string
url string
//nr_downloads int
}
fn test_orm() {
/*
db := pg.connect('vpm', 'alex')
//nr_modules := db.select count from modules
//nr_modules := db.select count from Modules where id == 1
nr_modules := db.select count from Modules where
name == 'Bob' && id == 1
println(nr_modules)
mod := db.select from Modules where id = 1 limit 1
println(mod)
mods := db.select from Modules limit 10
for mod in mods {
println(mod)
}
*/
/*
mod := db.retrieve<Module>(1)
mod := db.update Module set name = name + '!' where id > 10
nr_modules := db.select count from Modules
where id > 1 && name == ''
println(nr_modules)
nr_modules := db.select count from modules
nr_modules := db.select from modules
nr_modules := db[:modules].select
*/
/*
mod := select from db.modules where id = 1 limit 1
println(mod.name)
top_mods := select from db.modules where nr_downloads > 1000 order by nr_downloads desc limit 10
top_mods := db.select from modules where nr_downloads > 1000 order by nr_downloads desc limit 10
top_mods := db.select<Module>(m => m.nr_downloads > 1000).order_by(m => m.nr_downloads).desc().limit(10)
names := select name from db.modules // []string
n := db.q_int('select count(*) from modules')
println(n)
*/
}

View File

@ -1,162 +0,0 @@
module pg
#flag -lpq
#flag linux -I/usr/include/postgresql
#flag darwin -I/opt/local/include/postgresql11
#include <libpq-fe.h>
pub struct DB {
mut:
conn &C.PGconn
}
pub struct Row {
pub mut:
vals []string
}
struct C.PGResult { }
pub struct Config {
pub:
host string
port int = 5432
user string
password string
dbname string
}
fn C.PQconnectdb(a byteptr) &C.PGconn
fn C.PQerrorMessage(voidptr) byteptr
fn C.PQgetvalue(voidptr, int, int) byteptr
fn C.PQstatus(voidptr) int
fn C.PQntuples(voidptr) int
fn C.PQnfields(voidptr) int
fn C.PQexec(voidptr) voidptr
fn C.PQexecParams(voidptr) voidptr
pub fn connect(config Config) ?DB {
conninfo := 'host=$config.host port=$config.port user=$config.user dbname=$config.dbname password=$config.password'
conn := C.PQconnectdb(conninfo.str)
status := C.PQstatus(conn)
println("status=$status")
if status != C.CONNECTION_OK {
error_msg := C.PQerrorMessage(conn)
return error ('Connection to a PG database failed: ' + string(error_msg))
}
return DB {conn: conn}
}
fn res_to_rows(res voidptr) []Row {
nr_rows := C.PQntuples(res)
nr_cols := C.PQnfields(res)
mut rows := []Row
for i in 0..nr_rows {
mut row := Row{}
for j in 0..nr_cols {
val := C.PQgetvalue(res, i, j)
row.vals << string(val)
}
rows << row
}
return rows
}
pub fn (db DB) q_int(query string) int {
rows := db.exec(query)
if rows.len == 0 {
println('q_int "$query" not found')
return 0
}
row := rows[0]
if row.vals.len == 0 {
return 0
}
val := row.vals[0]
return val.int()
}
pub fn (db DB) q_string(query string) string {
rows := db.exec(query)
if rows.len == 0 {
println('q_string "$query" not found')
return ''
}
row := rows[0]
if row.vals.len == 0 {
return ''
}
val := row.vals[0]
return val
}
pub fn (db DB) q_strings(query string) []Row {
return db.exec(query)
}
pub fn (db DB) exec(query string) []Row {
res := C.PQexec(db.conn, query.str)
e := string(C.PQerrorMessage(db.conn))
if e != '' {
println('pg exec error:')
println(e)
return res_to_rows(res)
}
return res_to_rows(res)
}
fn rows_first_or_empty(rows []Row) ?Row {
if rows.len == 0 {
return error('no row')
}
return rows[0]
}
pub fn (db DB) exec_one(query string) ?Row {
res := C.PQexec(db.conn, query.str)
e := string(C.PQerrorMessage(db.conn))
if e != '' {
return error('pg exec error: "$e"')
}
row := rows_first_or_empty( res_to_rows(res) )
return row
}
// The entire function can be considered unsafe because of the malloc and the
// free. This prevents warnings and doesn't seem to affect behavior.
pub fn (db DB) exec_param_many(query string, params []string) []Row {
unsafe {
mut param_vals := &byteptr( malloc( params.len * sizeof(byteptr) ) )
for i in 0..params.len {
param_vals[i] = params[i].str
}
res := C.PQexecParams(db.conn, query.str, params.len, 0, param_vals, 0, 0, 0)
free(param_vals)
return db.handle_error_or_result(res, 'exec_param_many')
}
}
pub fn (db DB) exec_param2(query string, param, param2 string) []Row {
mut param_vals := [2]byteptr
param_vals[0] = param.str
param_vals[1] = param2.str
res := C.PQexecParams(db.conn, query.str, 2, 0, param_vals, 0, 0, 0)
return db.handle_error_or_result(res, 'exec_param2')
}
pub fn (db DB) exec_param(query string, param string) []Row {
mut param_vals := [1]byteptr
param_vals[0] = param.str
res := C.PQexecParams(db.conn, query.str, 1, 0, param_vals, 0, 0, 0)
return db.handle_error_or_result(res, 'exec_param')
}
fn (db DB) handle_error_or_result(res voidptr, elabel string) []Row {
e := string(C.PQerrorMessage(db.conn))
if e != '' {
println('pg $elabel error:')
println(e)
return res_to_rows(res)
}
return res_to_rows(res)
}

View File

@ -1,25 +0,0 @@
Before you can use this module, you must first have PostgreSQL installed on
your system. To do this, find your OS and perform the actions listed.
**NOTE**: These instructions are meant only as a convenience. If your OS is not
listed or you need extra help, [go here](https://www.postgresql.org/download/).
### Fedora 31
```
sudo dnf install postgresql-server postgresql-contrib
sudo systemctl enable postgresql # to autostart on startup
sudo systemctl start postgresql
```
### Debian 10/11
```
sudo apt-get install postgresql postgresql-client
sudo systemctl enable postgresql # to autostart on startup
sudo systemctl start postgresql
```
### MacOSX (Homebrew)
```
brew install postgresql
brew services start postgresql
```

View File

@ -1,12 +0,0 @@
# to use module `sqlite`, install `sqlite-devel` first.
for **Fedora 31**:
sudo dnf -y install `sqlite-devel`
for **Ubuntu 20.04**:
sudo apt install -y `libsqlite3-dev`

View File

@ -1,103 +0,0 @@
module sqlite
#flag -lsqlite3
#flag freebsd -I/usr/local/include
#flag freebsd -Wl -L/usr/local/lib -lsqlite3
#include "sqlite3.h"
struct C.sqlite3 {}
struct C.sqlite3_stmt {}
pub struct DB {
mut:
conn &C.sqlite3
}
pub struct Row {
pub mut:
vals []string
}
fn C.sqlite3_column_text(voidptr, int) byteptr
fn C.sqlite3_column_int(voidptr, int) int
fn C.sqlite3_open()
fn C.sqlite3_step() int
fn C.sqlite3_prepare_v2()
fn C.sqlite3_finalize()
fn C.sqlite3_column_count(voidptr) int
// Opens the connection with a database.
pub fn connect(path string) DB {
db := &C.sqlite3(0)
C.sqlite3_open(path.str, &db)
return DB{
conn: db
}
}
// Returns a single cell with value int.
pub fn (db DB) q_int(query string) int {
stmt := &C.sqlite3_stmt(0)
C.sqlite3_prepare_v2(db.conn, query.str, -1, &stmt, 0)
C.sqlite3_step(stmt)
res := C.sqlite3_column_int(stmt, 0)
C.sqlite3_finalize(stmt)
return res
}
// Returns a single cell with value string.
pub fn (db DB) q_string(query string) string {
stmt := &C.sqlite3_stmt(0)
C.sqlite3_prepare_v2(db.conn, query.str, -1, &stmt, 0)
C.sqlite3_step(stmt)
res := tos_clone(C.sqlite3_column_text(stmt, 0))
C.sqlite3_finalize(stmt)
return res
}
// Execute the query on db, return an array of all the results, alongside any result code.
// Result codes: https://www.sqlite.org/rescode.html
pub fn (db DB) exec(query string) ([]Row,int) {
stmt := &C.sqlite3_stmt(0)
C.sqlite3_prepare_v2(db.conn, query.str, -1, &stmt, 0)
nr_cols := C.sqlite3_column_count(stmt)
mut res := 0
mut rows := []Row
for {
res = C.sqlite3_step(stmt)
// Result Code SQLITE_ROW; Another row is available
if res != 100 {
break
}
mut row := Row{}
for i in 0 .. nr_cols {
val := tos_clone(C.sqlite3_column_text(stmt, i))
row.vals << val
}
rows << row
}
return rows,res
}
// Execute a query, handle error code
// Return the first row from the resulting table
pub fn (db DB) exec_one(query string) ?Row {
rows,code := db.exec(query)
if rows.len == 0 || code != 101 {
return error('SQL Error: Rows #$rows.len Return code $code')
}
return rows[0]
}
// In case you don't expect any result, but still want an error code
// e.g. INSERT INTO ... VALUES (...)
pub fn (db DB) exec_none(query string) int {
_,code := db.exec(query)
return code
}
/* TODO
pub fn (db DB) exec_param(query string, param string) []Row {
}
*/

View File

@ -1,29 +0,0 @@
import db.sqlite
fn test_sqlite() {
db := sqlite.connect(':memory:')
db.exec("drop table if exists users")
db.exec("create table users (id integer primary key, name text default '');")
db.exec("insert into users (name) values ('Sam')")
db.exec("insert into users (name) values ('Peter')")
db.exec("insert into users (name) values ('Kate')")
nr_users := db.q_int('select count(*) from users')
assert nr_users == 3
name := db.q_string('select name from users where id = 1')
assert name == 'Sam'
users, mut code := db.exec('select * from users')
assert users.len == 3
assert code == 101
code = db.exec_none('vacuum')
assert code == 101
user := db.exec_one('select * from users where id = 3') or {
panic(err)
}
assert user.vals.len == 2
}