lib/impure - Dropped 'T' from types
This commit is contained in:
parent
6ca3504dfb
commit
ea03fc6886
7 changed files with 165 additions and 157 deletions
|
|
@ -13,27 +13,28 @@
|
||||||
import strutils, mysql
|
import strutils, mysql
|
||||||
|
|
||||||
type
|
type
|
||||||
TDbConn* = PMySQL ## encapsulates a database connection
|
DbConn* = PMySQL ## encapsulates a database connection
|
||||||
TRow* = seq[string] ## a row of a dataset. NULL database values will be
|
Row* = seq[string] ## a row of a dataset. NULL database values will be
|
||||||
## transformed always to the empty string.
|
## transformed always to the empty string.
|
||||||
EDb* = object of IOError ## exception that is raised if a database error occurs
|
EDb* = object of IOError ## exception that is raised if a database error occurs
|
||||||
|
|
||||||
TSqlQuery* = distinct string ## an SQL query string
|
SqlQuery* = distinct string ## an SQL query string
|
||||||
|
|
||||||
FDb* = object of IOEffect ## effect that denotes a database operation
|
FDb* = object of IOEffect ## effect that denotes a database operation
|
||||||
FReadDb* = object of FDb ## effect that denotes a read operation
|
FReadDb* = object of FDb ## effect that denotes a read operation
|
||||||
FWriteDb* = object of FDb ## effect that denotes a write operation
|
FWriteDb* = object of FDb ## effect that denotes a write operation
|
||||||
|
{.deprecated: [TRow: Row, TSqlQuery: SqlQuery, TDbConn: DbConn].}
|
||||||
|
|
||||||
proc sql*(query: string): TSqlQuery {.noSideEffect, inline.} =
|
proc sql*(query: string): SqlQuery {.noSideEffect, inline.} =
|
||||||
## constructs a TSqlQuery from the string `query`. This is supposed to be
|
## constructs a SqlQuery from the string `query`. This is supposed to be
|
||||||
## used as a raw-string-literal modifier:
|
## used as a raw-string-literal modifier:
|
||||||
## ``sql"update user set counter = counter + 1"``
|
## ``sql"update user set counter = counter + 1"``
|
||||||
##
|
##
|
||||||
## If assertions are turned off, it does nothing. If assertions are turned
|
## If assertions are turned off, it does nothing. If assertions are turned
|
||||||
## on, later versions will check the string for valid syntax.
|
## on, later versions will check the string for valid syntax.
|
||||||
result = TSqlQuery(query)
|
result = SqlQuery(query)
|
||||||
|
|
||||||
proc dbError(db: TDbConn) {.noreturn.} =
|
proc dbError(db: DbConn) {.noreturn.} =
|
||||||
## raises an EDb exception.
|
## raises an EDb exception.
|
||||||
var e: ref EDb
|
var e: ref EDb
|
||||||
new(e)
|
new(e)
|
||||||
|
|
@ -48,7 +49,7 @@ proc dbError*(msg: string) {.noreturn.} =
|
||||||
raise e
|
raise e
|
||||||
|
|
||||||
when false:
|
when false:
|
||||||
proc dbQueryOpt*(db: TDbConn, query: string, args: varargs[string, `$`]) =
|
proc dbQueryOpt*(db: DbConn, query: string, args: varargs[string, `$`]) =
|
||||||
var stmt = mysql_stmt_init(db)
|
var stmt = mysql_stmt_init(db)
|
||||||
if stmt == nil: dbError(db)
|
if stmt == nil: dbError(db)
|
||||||
if mysql_stmt_prepare(stmt, query, len(query)) != 0:
|
if mysql_stmt_prepare(stmt, query, len(query)) != 0:
|
||||||
|
|
@ -65,7 +66,7 @@ proc dbQuote*(s: string): string =
|
||||||
else: add(result, c)
|
else: add(result, c)
|
||||||
add(result, '\'')
|
add(result, '\'')
|
||||||
|
|
||||||
proc dbFormat(formatstr: TSqlQuery, args: varargs[string]): string =
|
proc dbFormat(formatstr: SqlQuery, args: varargs[string]): string =
|
||||||
result = ""
|
result = ""
|
||||||
var a = 0
|
var a = 0
|
||||||
for c in items(string(formatstr)):
|
for c in items(string(formatstr)):
|
||||||
|
|
@ -78,23 +79,23 @@ proc dbFormat(formatstr: TSqlQuery, args: varargs[string]): string =
|
||||||
else:
|
else:
|
||||||
add(result, c)
|
add(result, c)
|
||||||
|
|
||||||
proc tryExec*(db: TDbConn, query: TSqlQuery, args: varargs[string, `$`]): bool {.
|
proc tryExec*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]): bool {.
|
||||||
tags: [FReadDB, FWriteDb].} =
|
tags: [FReadDB, FWriteDb].} =
|
||||||
## tries to execute the query and returns true if successful, false otherwise.
|
## tries to execute the query and returns true if successful, false otherwise.
|
||||||
var q = dbFormat(query, args)
|
var q = dbFormat(query, args)
|
||||||
return mysql.realQuery(db, q, q.len) == 0'i32
|
return mysql.realQuery(db, q, q.len) == 0'i32
|
||||||
|
|
||||||
proc rawExec(db: TDbConn, query: TSqlQuery, args: varargs[string, `$`]) =
|
proc rawExec(db: DbConn, query: SqlQuery, args: varargs[string, `$`]) =
|
||||||
var q = dbFormat(query, args)
|
var q = dbFormat(query, args)
|
||||||
if mysql.realQuery(db, q, q.len) != 0'i32: dbError(db)
|
if mysql.realQuery(db, q, q.len) != 0'i32: dbError(db)
|
||||||
|
|
||||||
proc exec*(db: TDbConn, query: TSqlQuery, args: varargs[string, `$`]) {.
|
proc exec*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]) {.
|
||||||
tags: [FReadDB, FWriteDb].} =
|
tags: [FReadDB, FWriteDb].} =
|
||||||
## executes the query and raises EDB if not successful.
|
## executes the query and raises EDB if not successful.
|
||||||
var q = dbFormat(query, args)
|
var q = dbFormat(query, args)
|
||||||
if mysql.realQuery(db, q, q.len) != 0'i32: dbError(db)
|
if mysql.realQuery(db, q, q.len) != 0'i32: dbError(db)
|
||||||
|
|
||||||
proc newRow(L: int): TRow =
|
proc newRow(L: int): Row =
|
||||||
newSeq(result, L)
|
newSeq(result, L)
|
||||||
for i in 0..L-1: result[i] = ""
|
for i in 0..L-1: result[i] = ""
|
||||||
|
|
||||||
|
|
@ -103,8 +104,8 @@ proc properFreeResult(sqlres: mysql.PRES, row: cstringArray) =
|
||||||
while mysql.fetchRow(sqlres) != nil: discard
|
while mysql.fetchRow(sqlres) != nil: discard
|
||||||
mysql.freeResult(sqlres)
|
mysql.freeResult(sqlres)
|
||||||
|
|
||||||
iterator fastRows*(db: TDbConn, query: TSqlQuery,
|
iterator fastRows*(db: DbConn, query: SqlQuery,
|
||||||
args: varargs[string, `$`]): TRow {.tags: [FReadDB].} =
|
args: varargs[string, `$`]): Row {.tags: [FReadDB].} =
|
||||||
## executes the query and iterates over the result dataset. This is very
|
## executes the query and iterates over the result dataset. This is very
|
||||||
## fast, but potenially dangerous: If the for-loop-body executes another
|
## fast, but potenially dangerous: If the for-loop-body executes another
|
||||||
## query, the results can be undefined. For MySQL this is the case!.
|
## query, the results can be undefined. For MySQL this is the case!.
|
||||||
|
|
@ -126,10 +127,10 @@ iterator fastRows*(db: TDbConn, query: TSqlQuery,
|
||||||
yield result
|
yield result
|
||||||
properFreeResult(sqlres, row)
|
properFreeResult(sqlres, row)
|
||||||
|
|
||||||
proc getRow*(db: TDbConn, query: TSqlQuery,
|
proc getRow*(db: DbConn, query: SqlQuery,
|
||||||
args: varargs[string, `$`]): TRow {.tags: [FReadDB].} =
|
args: varargs[string, `$`]): Row {.tags: [FReadDB].} =
|
||||||
## retrieves a single row. If the query doesn't return any rows, this proc
|
## retrieves a single row. If the query doesn't return any rows, this proc
|
||||||
## will return a TRow with empty strings for each column.
|
## will return a Row with empty strings for each column.
|
||||||
rawExec(db, query, args)
|
rawExec(db, query, args)
|
||||||
var sqlres = mysql.useResult(db)
|
var sqlres = mysql.useResult(db)
|
||||||
if sqlres != nil:
|
if sqlres != nil:
|
||||||
|
|
@ -145,8 +146,8 @@ proc getRow*(db: TDbConn, query: TSqlQuery,
|
||||||
add(result[i], row[i])
|
add(result[i], row[i])
|
||||||
properFreeResult(sqlres, row)
|
properFreeResult(sqlres, row)
|
||||||
|
|
||||||
proc getAllRows*(db: TDbConn, query: TSqlQuery,
|
proc getAllRows*(db: DbConn, query: SqlQuery,
|
||||||
args: varargs[string, `$`]): seq[TRow] {.tags: [FReadDB].} =
|
args: varargs[string, `$`]): seq[Row] {.tags: [FReadDB].} =
|
||||||
## executes the query and returns the whole result dataset.
|
## executes the query and returns the whole result dataset.
|
||||||
result = @[]
|
result = @[]
|
||||||
rawExec(db, query, args)
|
rawExec(db, query, args)
|
||||||
|
|
@ -168,12 +169,12 @@ proc getAllRows*(db: TDbConn, query: TSqlQuery,
|
||||||
inc(j)
|
inc(j)
|
||||||
mysql.freeResult(sqlres)
|
mysql.freeResult(sqlres)
|
||||||
|
|
||||||
iterator rows*(db: TDbConn, query: TSqlQuery,
|
iterator rows*(db: DbConn, query: SqlQuery,
|
||||||
args: varargs[string, `$`]): TRow {.tags: [FReadDB].} =
|
args: varargs[string, `$`]): Row {.tags: [FReadDB].} =
|
||||||
## same as `fastRows`, but slower and safe.
|
## same as `fastRows`, but slower and safe.
|
||||||
for r in items(getAllRows(db, query, args)): yield r
|
for r in items(getAllRows(db, query, args)): yield r
|
||||||
|
|
||||||
proc getValue*(db: TDbConn, query: TSqlQuery,
|
proc getValue*(db: DbConn, query: SqlQuery,
|
||||||
args: varargs[string, `$`]): string {.tags: [FReadDB].} =
|
args: varargs[string, `$`]): string {.tags: [FReadDB].} =
|
||||||
## executes the query and returns the first column of the first row of the
|
## executes the query and returns the first column of the first row of the
|
||||||
## result dataset. Returns "" if the dataset contains no rows or the database
|
## result dataset. Returns "" if the dataset contains no rows or the database
|
||||||
|
|
@ -183,7 +184,7 @@ proc getValue*(db: TDbConn, query: TSqlQuery,
|
||||||
result = row[0]
|
result = row[0]
|
||||||
break
|
break
|
||||||
|
|
||||||
proc tryInsertId*(db: TDbConn, query: TSqlQuery,
|
proc tryInsertId*(db: DbConn, query: SqlQuery,
|
||||||
args: varargs[string, `$`]): int64 {.tags: [FWriteDb].} =
|
args: varargs[string, `$`]): int64 {.tags: [FWriteDb].} =
|
||||||
## executes the query (typically "INSERT") and returns the
|
## executes the query (typically "INSERT") and returns the
|
||||||
## generated ID for the row or -1 in case of an error.
|
## generated ID for the row or -1 in case of an error.
|
||||||
|
|
@ -193,14 +194,14 @@ proc tryInsertId*(db: TDbConn, query: TSqlQuery,
|
||||||
else:
|
else:
|
||||||
result = mysql.insertId(db)
|
result = mysql.insertId(db)
|
||||||
|
|
||||||
proc insertId*(db: TDbConn, query: TSqlQuery,
|
proc insertId*(db: DbConn, query: SqlQuery,
|
||||||
args: varargs[string, `$`]): int64 {.tags: [FWriteDb].} =
|
args: varargs[string, `$`]): int64 {.tags: [FWriteDb].} =
|
||||||
## executes the query (typically "INSERT") and returns the
|
## executes the query (typically "INSERT") and returns the
|
||||||
## generated ID for the row.
|
## generated ID for the row.
|
||||||
result = tryInsertID(db, query, args)
|
result = tryInsertID(db, query, args)
|
||||||
if result < 0: dbError(db)
|
if result < 0: dbError(db)
|
||||||
|
|
||||||
proc execAffectedRows*(db: TDbConn, query: TSqlQuery,
|
proc execAffectedRows*(db: DbConn, query: SqlQuery,
|
||||||
args: varargs[string, `$`]): int64 {.
|
args: varargs[string, `$`]): int64 {.
|
||||||
tags: [FReadDB, FWriteDb].} =
|
tags: [FReadDB, FWriteDb].} =
|
||||||
## runs the query (typically "UPDATE") and returns the
|
## runs the query (typically "UPDATE") and returns the
|
||||||
|
|
@ -208,11 +209,11 @@ proc execAffectedRows*(db: TDbConn, query: TSqlQuery,
|
||||||
rawExec(db, query, args)
|
rawExec(db, query, args)
|
||||||
result = mysql.affectedRows(db)
|
result = mysql.affectedRows(db)
|
||||||
|
|
||||||
proc close*(db: TDbConn) {.tags: [FDb].} =
|
proc close*(db: DbConn) {.tags: [FDb].} =
|
||||||
## closes the database connection.
|
## closes the database connection.
|
||||||
if db != nil: mysql.close(db)
|
if db != nil: mysql.close(db)
|
||||||
|
|
||||||
proc open*(connection, user, password, database: string): TDbConn {.
|
proc open*(connection, user, password, database: string): DbConn {.
|
||||||
tags: [FDb].} =
|
tags: [FDb].} =
|
||||||
## opens a database connection. Raises `EDb` if the connection could not
|
## opens a database connection. Raises `EDb` if the connection could not
|
||||||
## be established.
|
## be established.
|
||||||
|
|
@ -230,8 +231,8 @@ proc open*(connection, user, password, database: string): TDbConn {.
|
||||||
db_mysql.close(result)
|
db_mysql.close(result)
|
||||||
dbError(errmsg)
|
dbError(errmsg)
|
||||||
|
|
||||||
proc setEncoding*(connection: TDbConn, encoding: string): bool {.
|
proc setEncoding*(connection: DbConn, encoding: string): bool {.
|
||||||
tags: [FDb].} =
|
tags: [FDb].} =
|
||||||
## sets the encoding of a database connection, returns true for
|
## sets the encoding of a database connection, returns true for
|
||||||
## success, false for failure.
|
## success, false for failure.
|
||||||
result = mysql.set_character_set(connection, encoding) == 0
|
result = mysql.set_character_set(connection, encoding) == 0
|
||||||
|
|
|
||||||
|
|
@ -13,28 +13,30 @@
|
||||||
import strutils, postgres
|
import strutils, postgres
|
||||||
|
|
||||||
type
|
type
|
||||||
TDbConn* = PPGconn ## encapsulates a database connection
|
DbConn* = PPGconn ## encapsulates a database connection
|
||||||
TRow* = seq[string] ## a row of a dataset. NULL database values will be
|
Row* = seq[string] ## a row of a dataset. NULL database values will be
|
||||||
## transformed always to the empty string.
|
## transformed always to the empty string.
|
||||||
EDb* = object of IOError ## exception that is raised if a database error occurs
|
EDb* = object of IOError ## exception that is raised if a database error occurs
|
||||||
|
|
||||||
TSqlQuery* = distinct string ## an SQL query string
|
SqlQuery* = distinct string ## an SQL query string
|
||||||
TSqlPrepared* = distinct string ## a identifier for the prepared queries
|
SqlPrepared* = distinct string ## a identifier for the prepared queries
|
||||||
|
|
||||||
FDb* = object of IOEffect ## effect that denotes a database operation
|
FDb* = object of IOEffect ## effect that denotes a database operation
|
||||||
FReadDb* = object of FDb ## effect that denotes a read operation
|
FReadDb* = object of FDb ## effect that denotes a read operation
|
||||||
FWriteDb* = object of FDb ## effect that denotes a write operation
|
FWriteDb* = object of FDb ## effect that denotes a write operation
|
||||||
|
{.deprecated: [TRow: Row, TSqlQuery: SqlQuery, TDbConn: DbConn,
|
||||||
|
TSqlPrepared: SqlPrepared].}
|
||||||
|
|
||||||
proc sql*(query: string): TSqlQuery {.noSideEffect, inline.} =
|
proc sql*(query: string): SqlQuery {.noSideEffect, inline.} =
|
||||||
## constructs a TSqlQuery from the string `query`. This is supposed to be
|
## constructs a SqlQuery from the string `query`. This is supposed to be
|
||||||
## used as a raw-string-literal modifier:
|
## used as a raw-string-literal modifier:
|
||||||
## ``sql"update user set counter = counter + 1"``
|
## ``sql"update user set counter = counter + 1"``
|
||||||
##
|
##
|
||||||
## If assertions are turned off, it does nothing. If assertions are turned
|
## If assertions are turned off, it does nothing. If assertions are turned
|
||||||
## on, later versions will check the string for valid syntax.
|
## on, later versions will check the string for valid syntax.
|
||||||
result = TSqlQuery(query)
|
result = SqlQuery(query)
|
||||||
|
|
||||||
proc dbError*(db: TDbConn) {.noreturn.} =
|
proc dbError*(db: DbConn) {.noreturn.} =
|
||||||
## raises an EDb exception.
|
## raises an EDb exception.
|
||||||
var e: ref EDb
|
var e: ref EDb
|
||||||
new(e)
|
new(e)
|
||||||
|
|
@ -56,7 +58,7 @@ proc dbQuote*(s: string): string =
|
||||||
else: add(result, c)
|
else: add(result, c)
|
||||||
add(result, '\'')
|
add(result, '\'')
|
||||||
|
|
||||||
proc dbFormat(formatstr: TSqlQuery, args: varargs[string]): string =
|
proc dbFormat(formatstr: SqlQuery, args: varargs[string]): string =
|
||||||
result = ""
|
result = ""
|
||||||
var a = 0
|
var a = 0
|
||||||
for c in items(string(formatstr)):
|
for c in items(string(formatstr)):
|
||||||
|
|
@ -69,7 +71,7 @@ proc dbFormat(formatstr: TSqlQuery, args: varargs[string]): string =
|
||||||
else:
|
else:
|
||||||
add(result, c)
|
add(result, c)
|
||||||
|
|
||||||
proc tryExec*(db: TDbConn, query: TSqlQuery,
|
proc tryExec*(db: DbConn, query: SqlQuery,
|
||||||
args: varargs[string, `$`]): bool {.tags: [FReadDB, FWriteDb].} =
|
args: varargs[string, `$`]): bool {.tags: [FReadDB, FWriteDb].} =
|
||||||
## tries to execute the query and returns true if successful, false otherwise.
|
## tries to execute the query and returns true if successful, false otherwise.
|
||||||
var arr = allocCStringArray(args)
|
var arr = allocCStringArray(args)
|
||||||
|
|
@ -79,7 +81,7 @@ proc tryExec*(db: TDbConn, query: TSqlQuery,
|
||||||
result = pqresultStatus(res) == PGRES_COMMAND_OK
|
result = pqresultStatus(res) == PGRES_COMMAND_OK
|
||||||
pqclear(res)
|
pqclear(res)
|
||||||
|
|
||||||
proc exec*(db: TDbConn, query: TSqlQuery, args: varargs[string, `$`]) {.
|
proc exec*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]) {.
|
||||||
tags: [FReadDB, FWriteDb].} =
|
tags: [FReadDB, FWriteDb].} =
|
||||||
## executes the query and raises EDB if not successful.
|
## executes the query and raises EDB if not successful.
|
||||||
var arr = allocCStringArray(args)
|
var arr = allocCStringArray(args)
|
||||||
|
|
@ -89,7 +91,7 @@ proc exec*(db: TDbConn, query: TSqlQuery, args: varargs[string, `$`]) {.
|
||||||
if pqresultStatus(res) != PGRES_COMMAND_OK: dbError(db)
|
if pqresultStatus(res) != PGRES_COMMAND_OK: dbError(db)
|
||||||
pqclear(res)
|
pqclear(res)
|
||||||
|
|
||||||
proc exec*(db: TDbConn, stmtName: TSqlPrepared,
|
proc exec*(db: DbConn, stmtName: SqlPrepared,
|
||||||
args: varargs[string]) {.tags: [FReadDB, FWriteDb].} =
|
args: varargs[string]) {.tags: [FReadDB, FWriteDb].} =
|
||||||
var arr = allocCStringArray(args)
|
var arr = allocCStringArray(args)
|
||||||
var res = pqexecPrepared(db, stmtName.string, int32(args.len), arr,
|
var res = pqexecPrepared(db, stmtName.string, int32(args.len), arr,
|
||||||
|
|
@ -98,11 +100,11 @@ proc exec*(db: TDbConn, stmtName: TSqlPrepared,
|
||||||
if pqResultStatus(res) != PGRES_COMMAND_OK: dbError(db)
|
if pqResultStatus(res) != PGRES_COMMAND_OK: dbError(db)
|
||||||
pqclear(res)
|
pqclear(res)
|
||||||
|
|
||||||
proc newRow(L: int): TRow =
|
proc newRow(L: int): Row =
|
||||||
newSeq(result, L)
|
newSeq(result, L)
|
||||||
for i in 0..L-1: result[i] = ""
|
for i in 0..L-1: result[i] = ""
|
||||||
|
|
||||||
proc setupQuery(db: TDbConn, query: TSqlQuery,
|
proc setupQuery(db: DbConn, query: SqlQuery,
|
||||||
args: varargs[string]): PPGresult =
|
args: varargs[string]): PPGresult =
|
||||||
var arr = allocCStringArray(args)
|
var arr = allocCStringArray(args)
|
||||||
result = pqexecParams(db, query.string, int32(args.len), nil, arr,
|
result = pqexecParams(db, query.string, int32(args.len), nil, arr,
|
||||||
|
|
@ -110,7 +112,7 @@ proc setupQuery(db: TDbConn, query: TSqlQuery,
|
||||||
deallocCStringArray(arr)
|
deallocCStringArray(arr)
|
||||||
if pqResultStatus(result) != PGRES_TUPLES_OK: dbError(db)
|
if pqResultStatus(result) != PGRES_TUPLES_OK: dbError(db)
|
||||||
|
|
||||||
proc setupQuery(db: TDbConn, stmtName: TSqlPrepared,
|
proc setupQuery(db: DbConn, stmtName: SqlPrepared,
|
||||||
args: varargs[string]): PPGresult =
|
args: varargs[string]): PPGresult =
|
||||||
var arr = allocCStringArray(args)
|
var arr = allocCStringArray(args)
|
||||||
result = pqexecPrepared(db, stmtName.string, int32(args.len), arr,
|
result = pqexecPrepared(db, stmtName.string, int32(args.len), arr,
|
||||||
|
|
@ -118,13 +120,13 @@ proc setupQuery(db: TDbConn, stmtName: TSqlPrepared,
|
||||||
deallocCStringArray(arr)
|
deallocCStringArray(arr)
|
||||||
if pqResultStatus(result) != PGRES_TUPLES_OK: dbError(db)
|
if pqResultStatus(result) != PGRES_TUPLES_OK: dbError(db)
|
||||||
|
|
||||||
proc prepare*(db: TDbConn; stmtName: string, query: TSqlQuery;
|
proc prepare*(db: DbConn; stmtName: string, query: SqlQuery;
|
||||||
nParams: int): TSqlPrepared =
|
nParams: int): SqlPrepared =
|
||||||
var res = pqprepare(db, stmtName, query.string, int32(nParams), nil)
|
var res = pqprepare(db, stmtName, query.string, int32(nParams), nil)
|
||||||
if pqResultStatus(res) != PGRES_COMMAND_OK: dbError(db)
|
if pqResultStatus(res) != PGRES_COMMAND_OK: dbError(db)
|
||||||
return TSqlPrepared(stmtName)
|
return SqlPrepared(stmtName)
|
||||||
|
|
||||||
proc setRow(res: PPGresult, r: var TRow, line, cols: int32) =
|
proc setRow(res: PPGresult, r: var Row, line, cols: int32) =
|
||||||
for col in 0..cols-1:
|
for col in 0..cols-1:
|
||||||
setLen(r[col], 0)
|
setLen(r[col], 0)
|
||||||
let x = pqgetvalue(res, line, col)
|
let x = pqgetvalue(res, line, col)
|
||||||
|
|
@ -133,8 +135,8 @@ proc setRow(res: PPGresult, r: var TRow, line, cols: int32) =
|
||||||
else:
|
else:
|
||||||
add(r[col], x)
|
add(r[col], x)
|
||||||
|
|
||||||
iterator fastRows*(db: TDbConn, query: TSqlQuery,
|
iterator fastRows*(db: DbConn, query: SqlQuery,
|
||||||
args: varargs[string, `$`]): TRow {.tags: [FReadDB].} =
|
args: varargs[string, `$`]): Row {.tags: [FReadDB].} =
|
||||||
## executes the query and iterates over the result dataset. This is very
|
## executes the query and iterates over the result dataset. This is very
|
||||||
## fast, but potenially dangerous: If the for-loop-body executes another
|
## fast, but potenially dangerous: If the for-loop-body executes another
|
||||||
## query, the results can be undefined. For Postgres it is safe though.
|
## query, the results can be undefined. For Postgres it is safe though.
|
||||||
|
|
@ -146,8 +148,8 @@ iterator fastRows*(db: TDbConn, query: TSqlQuery,
|
||||||
yield result
|
yield result
|
||||||
pqclear(res)
|
pqclear(res)
|
||||||
|
|
||||||
iterator fastRows*(db: TDbConn, stmtName: TSqlPrepared,
|
iterator fastRows*(db: DbConn, stmtName: SqlPrepared,
|
||||||
args: varargs[string, `$`]): TRow {.tags: [FReadDB].} =
|
args: varargs[string, `$`]): Row {.tags: [FReadDB].} =
|
||||||
## executes the prepared query and iterates over the result dataset.
|
## executes the prepared query and iterates over the result dataset.
|
||||||
var res = setupQuery(db, stmtName, args)
|
var res = setupQuery(db, stmtName, args)
|
||||||
var L = pqNfields(res)
|
var L = pqNfields(res)
|
||||||
|
|
@ -157,44 +159,44 @@ iterator fastRows*(db: TDbConn, stmtName: TSqlPrepared,
|
||||||
yield result
|
yield result
|
||||||
pqClear(res)
|
pqClear(res)
|
||||||
|
|
||||||
proc getRow*(db: TDbConn, query: TSqlQuery,
|
proc getRow*(db: DbConn, query: SqlQuery,
|
||||||
args: varargs[string, `$`]): TRow {.tags: [FReadDB].} =
|
args: varargs[string, `$`]): Row {.tags: [FReadDB].} =
|
||||||
## retrieves a single row. If the query doesn't return any rows, this proc
|
## retrieves a single row. If the query doesn't return any rows, this proc
|
||||||
## will return a TRow with empty strings for each column.
|
## will return a Row with empty strings for each column.
|
||||||
var res = setupQuery(db, query, args)
|
var res = setupQuery(db, query, args)
|
||||||
var L = pqnfields(res)
|
var L = pqnfields(res)
|
||||||
result = newRow(L)
|
result = newRow(L)
|
||||||
setRow(res, result, 0, L)
|
setRow(res, result, 0, L)
|
||||||
pqclear(res)
|
pqclear(res)
|
||||||
|
|
||||||
proc getRow*(db: TDbConn, stmtName: TSqlPrepared,
|
proc getRow*(db: DbConn, stmtName: SqlPrepared,
|
||||||
args: varargs[string, `$`]): TRow {.tags: [FReadDB].} =
|
args: varargs[string, `$`]): Row {.tags: [FReadDB].} =
|
||||||
var res = setupQuery(db, stmtName, args)
|
var res = setupQuery(db, stmtName, args)
|
||||||
var L = pqNfields(res)
|
var L = pqNfields(res)
|
||||||
result = newRow(L)
|
result = newRow(L)
|
||||||
setRow(res, result, 0, L)
|
setRow(res, result, 0, L)
|
||||||
pqClear(res)
|
pqClear(res)
|
||||||
|
|
||||||
proc getAllRows*(db: TDbConn, query: TSqlQuery,
|
proc getAllRows*(db: DbConn, query: SqlQuery,
|
||||||
args: varargs[string, `$`]): seq[TRow] {.tags: [FReadDB].} =
|
args: varargs[string, `$`]): seq[Row] {.tags: [FReadDB].} =
|
||||||
## executes the query and returns the whole result dataset.
|
## executes the query and returns the whole result dataset.
|
||||||
result = @[]
|
result = @[]
|
||||||
for r in fastRows(db, query, args):
|
for r in fastRows(db, query, args):
|
||||||
result.add(r)
|
result.add(r)
|
||||||
|
|
||||||
proc getAllRows*(db: TDbConn, stmtName: TSqlPrepared,
|
proc getAllRows*(db: DbConn, stmtName: SqlPrepared,
|
||||||
args: varargs[string, `$`]): seq[TRow] {.tags: [FReadDB].} =
|
args: varargs[string, `$`]): seq[Row] {.tags: [FReadDB].} =
|
||||||
## executes the prepared query and returns the whole result dataset.
|
## executes the prepared query and returns the whole result dataset.
|
||||||
result = @[]
|
result = @[]
|
||||||
for r in fastRows(db, stmtName, args):
|
for r in fastRows(db, stmtName, args):
|
||||||
result.add(r)
|
result.add(r)
|
||||||
|
|
||||||
iterator rows*(db: TDbConn, query: TSqlQuery,
|
iterator rows*(db: DbConn, query: SqlQuery,
|
||||||
args: varargs[string, `$`]): TRow {.tags: [FReadDB].} =
|
args: varargs[string, `$`]): Row {.tags: [FReadDB].} =
|
||||||
## same as `fastRows`, but slower and safe.
|
## same as `fastRows`, but slower and safe.
|
||||||
for r in items(getAllRows(db, query, args)): yield r
|
for r in items(getAllRows(db, query, args)): yield r
|
||||||
|
|
||||||
proc getValue*(db: TDbConn, query: TSqlQuery,
|
proc getValue*(db: DbConn, query: SqlQuery,
|
||||||
args: varargs[string, `$`]): string {.tags: [FReadDB].} =
|
args: varargs[string, `$`]): string {.tags: [FReadDB].} =
|
||||||
## executes the query and returns the first column of the first row of the
|
## executes the query and returns the first column of the first row of the
|
||||||
## result dataset. Returns "" if the dataset contains no rows or the database
|
## result dataset. Returns "" if the dataset contains no rows or the database
|
||||||
|
|
@ -202,20 +204,20 @@ proc getValue*(db: TDbConn, query: TSqlQuery,
|
||||||
var x = pqgetvalue(setupQuery(db, query, args), 0, 0)
|
var x = pqgetvalue(setupQuery(db, query, args), 0, 0)
|
||||||
result = if isNil(x): "" else: $x
|
result = if isNil(x): "" else: $x
|
||||||
|
|
||||||
proc tryInsertID*(db: TDbConn, query: TSqlQuery,
|
proc tryInsertID*(db: DbConn, query: SqlQuery,
|
||||||
args: varargs[string, `$`]): int64 {.tags: [FWriteDb].}=
|
args: varargs[string, `$`]): int64 {.tags: [FWriteDb].}=
|
||||||
## executes the query (typically "INSERT") and returns the
|
## executes the query (typically "INSERT") and returns the
|
||||||
## generated ID for the row or -1 in case of an error. For Postgre this adds
|
## generated ID for the row or -1 in case of an error. For Postgre this adds
|
||||||
## ``RETURNING id`` to the query, so it only works if your primary key is
|
## ``RETURNING id`` to the query, so it only works if your primary key is
|
||||||
## named ``id``.
|
## named ``id``.
|
||||||
var x = pqgetvalue(setupQuery(db, TSqlQuery(string(query) & " RETURNING id"),
|
var x = pqgetvalue(setupQuery(db, SqlQuery(string(query) & " RETURNING id"),
|
||||||
args), 0, 0)
|
args), 0, 0)
|
||||||
if not isNil(x):
|
if not isNil(x):
|
||||||
result = parseBiggestInt($x)
|
result = parseBiggestInt($x)
|
||||||
else:
|
else:
|
||||||
result = -1
|
result = -1
|
||||||
|
|
||||||
proc insertID*(db: TDbConn, query: TSqlQuery,
|
proc insertID*(db: DbConn, query: SqlQuery,
|
||||||
args: varargs[string, `$`]): int64 {.tags: [FWriteDb].} =
|
args: varargs[string, `$`]): int64 {.tags: [FWriteDb].} =
|
||||||
## executes the query (typically "INSERT") and returns the
|
## executes the query (typically "INSERT") and returns the
|
||||||
## generated ID for the row. For Postgre this adds
|
## generated ID for the row. For Postgre this adds
|
||||||
|
|
@ -224,7 +226,7 @@ proc insertID*(db: TDbConn, query: TSqlQuery,
|
||||||
result = tryInsertID(db, query, args)
|
result = tryInsertID(db, query, args)
|
||||||
if result < 0: dbError(db)
|
if result < 0: dbError(db)
|
||||||
|
|
||||||
proc execAffectedRows*(db: TDbConn, query: TSqlQuery,
|
proc execAffectedRows*(db: DbConn, query: SqlQuery,
|
||||||
args: varargs[string, `$`]): int64 {.tags: [
|
args: varargs[string, `$`]): int64 {.tags: [
|
||||||
FReadDB, FWriteDb].} =
|
FReadDB, FWriteDb].} =
|
||||||
## executes the query (typically "UPDATE") and returns the
|
## executes the query (typically "UPDATE") and returns the
|
||||||
|
|
@ -235,11 +237,11 @@ proc execAffectedRows*(db: TDbConn, query: TSqlQuery,
|
||||||
result = parseBiggestInt($pqcmdTuples(res))
|
result = parseBiggestInt($pqcmdTuples(res))
|
||||||
pqclear(res)
|
pqclear(res)
|
||||||
|
|
||||||
proc close*(db: TDbConn) {.tags: [FDb].} =
|
proc close*(db: DbConn) {.tags: [FDb].} =
|
||||||
## closes the database connection.
|
## closes the database connection.
|
||||||
if db != nil: pqfinish(db)
|
if db != nil: pqfinish(db)
|
||||||
|
|
||||||
proc open*(connection, user, password, database: string): TDbConn {.
|
proc open*(connection, user, password, database: string): DbConn {.
|
||||||
tags: [FDb].} =
|
tags: [FDb].} =
|
||||||
## opens a database connection. Raises `EDb` if the connection could not
|
## opens a database connection. Raises `EDb` if the connection could not
|
||||||
## be established.
|
## be established.
|
||||||
|
|
@ -261,8 +263,8 @@ proc open*(connection, user, password, database: string): TDbConn {.
|
||||||
result = pqsetdbLogin(nil, nil, nil, nil, database, user, password)
|
result = pqsetdbLogin(nil, nil, nil, nil, database, user, password)
|
||||||
if pqStatus(result) != CONNECTION_OK: dbError(result) # result = nil
|
if pqStatus(result) != CONNECTION_OK: dbError(result) # result = nil
|
||||||
|
|
||||||
proc setEncoding*(connection: TDbConn, encoding: string): bool {.
|
proc setEncoding*(connection: DbConn, encoding: string): bool {.
|
||||||
tags: [FDb].} =
|
tags: [FDb].} =
|
||||||
## sets the encoding of a database connection, returns true for
|
## sets the encoding of a database connection, returns true for
|
||||||
## success, false for failure.
|
## success, false for failure.
|
||||||
return pqsetClientEncoding(connection, encoding) == 0
|
return pqsetClientEncoding(connection, encoding) == 0
|
||||||
|
|
|
||||||
|
|
@ -13,27 +13,28 @@
|
||||||
import strutils, sqlite3
|
import strutils, sqlite3
|
||||||
|
|
||||||
type
|
type
|
||||||
TDbConn* = PSqlite3 ## encapsulates a database connection
|
DbConn* = PSqlite3 ## encapsulates a database connection
|
||||||
TRow* = seq[string] ## a row of a dataset. NULL database values will be
|
Row* = seq[string] ## a row of a dataset. NULL database values will be
|
||||||
## transformed always to the empty string.
|
## transformed always to the empty string.
|
||||||
EDb* = object of IOError ## exception that is raised if a database error occurs
|
EDb* = object of IOError ## exception that is raised if a database error occurs
|
||||||
|
|
||||||
TSqlQuery* = distinct string ## an SQL query string
|
SqlQuery* = distinct string ## an SQL query string
|
||||||
|
|
||||||
FDb* = object of IOEffect ## effect that denotes a database operation
|
FDb* = object of IOEffect ## effect that denotes a database operation
|
||||||
FReadDb* = object of FDb ## effect that denotes a read operation
|
FReadDb* = object of FDb ## effect that denotes a read operation
|
||||||
FWriteDb* = object of FDb ## effect that denotes a write operation
|
FWriteDb* = object of FDb ## effect that denotes a write operation
|
||||||
|
{.deprecated: [TRow: Row, TSqlQuery: SqlQuery, TDbConn: DbConn].}
|
||||||
|
|
||||||
proc sql*(query: string): TSqlQuery {.noSideEffect, inline.} =
|
proc sql*(query: string): SqlQuery {.noSideEffect, inline.} =
|
||||||
## constructs a TSqlQuery from the string `query`. This is supposed to be
|
## constructs a SqlQuery from the string `query`. This is supposed to be
|
||||||
## used as a raw-string-literal modifier:
|
## used as a raw-string-literal modifier:
|
||||||
## ``sql"update user set counter = counter + 1"``
|
## ``sql"update user set counter = counter + 1"``
|
||||||
##
|
##
|
||||||
## If assertions are turned off, it does nothing. If assertions are turned
|
## If assertions are turned off, it does nothing. If assertions are turned
|
||||||
## on, later versions will check the string for valid syntax.
|
## on, later versions will check the string for valid syntax.
|
||||||
result = TSqlQuery(query)
|
result = SqlQuery(query)
|
||||||
|
|
||||||
proc dbError(db: TDbConn) {.noreturn.} =
|
proc dbError(db: DbConn) {.noreturn.} =
|
||||||
## raises an EDb exception.
|
## raises an EDb exception.
|
||||||
var e: ref EDb
|
var e: ref EDb
|
||||||
new(e)
|
new(e)
|
||||||
|
|
@ -55,7 +56,7 @@ proc dbQuote(s: string): string =
|
||||||
else: add(result, c)
|
else: add(result, c)
|
||||||
add(result, '\'')
|
add(result, '\'')
|
||||||
|
|
||||||
proc dbFormat(formatstr: TSqlQuery, args: varargs[string]): string =
|
proc dbFormat(formatstr: SqlQuery, args: varargs[string]): string =
|
||||||
result = ""
|
result = ""
|
||||||
var a = 0
|
var a = 0
|
||||||
for c in items(string(formatstr)):
|
for c in items(string(formatstr)):
|
||||||
|
|
@ -65,7 +66,7 @@ proc dbFormat(formatstr: TSqlQuery, args: varargs[string]): string =
|
||||||
else:
|
else:
|
||||||
add(result, c)
|
add(result, c)
|
||||||
|
|
||||||
proc tryExec*(db: TDbConn, query: TSqlQuery,
|
proc tryExec*(db: DbConn, query: SqlQuery,
|
||||||
args: varargs[string, `$`]): bool {.tags: [FReadDb, FWriteDb].} =
|
args: varargs[string, `$`]): bool {.tags: [FReadDb, FWriteDb].} =
|
||||||
## tries to execute the query and returns true if successful, false otherwise.
|
## tries to execute the query and returns true if successful, false otherwise.
|
||||||
var q = dbFormat(query, args)
|
var q = dbFormat(query, args)
|
||||||
|
|
@ -74,29 +75,29 @@ proc tryExec*(db: TDbConn, query: TSqlQuery,
|
||||||
if step(stmt) == SQLITE_DONE:
|
if step(stmt) == SQLITE_DONE:
|
||||||
result = finalize(stmt) == SQLITE_OK
|
result = finalize(stmt) == SQLITE_OK
|
||||||
|
|
||||||
proc exec*(db: TDbConn, query: TSqlQuery, args: varargs[string, `$`]) {.
|
proc exec*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]) {.
|
||||||
tags: [FReadDb, FWriteDb].} =
|
tags: [FReadDb, FWriteDb].} =
|
||||||
## executes the query and raises EDB if not successful.
|
## executes the query and raises EDB if not successful.
|
||||||
if not tryExec(db, query, args): dbError(db)
|
if not tryExec(db, query, args): dbError(db)
|
||||||
|
|
||||||
proc newRow(L: int): TRow =
|
proc newRow(L: int): Row =
|
||||||
newSeq(result, L)
|
newSeq(result, L)
|
||||||
for i in 0..L-1: result[i] = ""
|
for i in 0..L-1: result[i] = ""
|
||||||
|
|
||||||
proc setupQuery(db: TDbConn, query: TSqlQuery,
|
proc setupQuery(db: DbConn, query: SqlQuery,
|
||||||
args: varargs[string]): Pstmt =
|
args: varargs[string]): Pstmt =
|
||||||
var q = dbFormat(query, args)
|
var q = dbFormat(query, args)
|
||||||
if prepare_v2(db, q, q.len.cint, result, nil) != SQLITE_OK: dbError(db)
|
if prepare_v2(db, q, q.len.cint, result, nil) != SQLITE_OK: dbError(db)
|
||||||
|
|
||||||
proc setRow(stmt: Pstmt, r: var TRow, cols: cint) =
|
proc setRow(stmt: Pstmt, r: var Row, cols: cint) =
|
||||||
for col in 0..cols-1:
|
for col in 0..cols-1:
|
||||||
setLen(r[col], column_bytes(stmt, col)) # set capacity
|
setLen(r[col], column_bytes(stmt, col)) # set capacity
|
||||||
setLen(r[col], 0)
|
setLen(r[col], 0)
|
||||||
let x = column_text(stmt, col)
|
let x = column_text(stmt, col)
|
||||||
if not isNil(x): add(r[col], x)
|
if not isNil(x): add(r[col], x)
|
||||||
|
|
||||||
iterator fastRows*(db: TDbConn, query: TSqlQuery,
|
iterator fastRows*(db: DbConn, query: SqlQuery,
|
||||||
args: varargs[string, `$`]): TRow {.tags: [FReadDb].} =
|
args: varargs[string, `$`]): Row {.tags: [FReadDb].} =
|
||||||
## executes the query and iterates over the result dataset. This is very
|
## executes the query and iterates over the result dataset. This is very
|
||||||
## fast, but potenially dangerous: If the for-loop-body executes another
|
## fast, but potenially dangerous: If the for-loop-body executes another
|
||||||
## query, the results can be undefined. For Sqlite it is safe though.
|
## query, the results can be undefined. For Sqlite it is safe though.
|
||||||
|
|
@ -108,10 +109,10 @@ iterator fastRows*(db: TDbConn, query: TSqlQuery,
|
||||||
yield result
|
yield result
|
||||||
if finalize(stmt) != SQLITE_OK: dbError(db)
|
if finalize(stmt) != SQLITE_OK: dbError(db)
|
||||||
|
|
||||||
proc getRow*(db: TDbConn, query: TSqlQuery,
|
proc getRow*(db: DbConn, query: SqlQuery,
|
||||||
args: varargs[string, `$`]): TRow {.tags: [FReadDb].} =
|
args: varargs[string, `$`]): Row {.tags: [FReadDb].} =
|
||||||
## retrieves a single row. If the query doesn't return any rows, this proc
|
## retrieves a single row. If the query doesn't return any rows, this proc
|
||||||
## will return a TRow with empty strings for each column.
|
## will return a Row with empty strings for each column.
|
||||||
var stmt = setupQuery(db, query, args)
|
var stmt = setupQuery(db, query, args)
|
||||||
var L = (column_count(stmt))
|
var L = (column_count(stmt))
|
||||||
result = newRow(L)
|
result = newRow(L)
|
||||||
|
|
@ -119,19 +120,19 @@ proc getRow*(db: TDbConn, query: TSqlQuery,
|
||||||
setRow(stmt, result, L)
|
setRow(stmt, result, L)
|
||||||
if finalize(stmt) != SQLITE_OK: dbError(db)
|
if finalize(stmt) != SQLITE_OK: dbError(db)
|
||||||
|
|
||||||
proc getAllRows*(db: TDbConn, query: TSqlQuery,
|
proc getAllRows*(db: DbConn, query: SqlQuery,
|
||||||
args: varargs[string, `$`]): seq[TRow] {.tags: [FReadDb].} =
|
args: varargs[string, `$`]): seq[Row] {.tags: [FReadDb].} =
|
||||||
## executes the query and returns the whole result dataset.
|
## executes the query and returns the whole result dataset.
|
||||||
result = @[]
|
result = @[]
|
||||||
for r in fastRows(db, query, args):
|
for r in fastRows(db, query, args):
|
||||||
result.add(r)
|
result.add(r)
|
||||||
|
|
||||||
iterator rows*(db: TDbConn, query: TSqlQuery,
|
iterator rows*(db: DbConn, query: SqlQuery,
|
||||||
args: varargs[string, `$`]): TRow {.tags: [FReadDb].} =
|
args: varargs[string, `$`]): Row {.tags: [FReadDb].} =
|
||||||
## same as `FastRows`, but slower and safe.
|
## same as `FastRows`, but slower and safe.
|
||||||
for r in fastRows(db, query, args): yield r
|
for r in fastRows(db, query, args): yield r
|
||||||
|
|
||||||
proc getValue*(db: TDbConn, query: TSqlQuery,
|
proc getValue*(db: DbConn, query: SqlQuery,
|
||||||
args: varargs[string, `$`]): string {.tags: [FReadDb].} =
|
args: varargs[string, `$`]): string {.tags: [FReadDb].} =
|
||||||
## executes the query and returns the first column of the first row of the
|
## executes the query and returns the first column of the first row of the
|
||||||
## result dataset. Returns "" if the dataset contains no rows or the database
|
## result dataset. Returns "" if the dataset contains no rows or the database
|
||||||
|
|
@ -148,7 +149,7 @@ proc getValue*(db: TDbConn, query: TSqlQuery,
|
||||||
result = ""
|
result = ""
|
||||||
if finalize(stmt) != SQLITE_OK: dbError(db)
|
if finalize(stmt) != SQLITE_OK: dbError(db)
|
||||||
|
|
||||||
proc tryInsertID*(db: TDbConn, query: TSqlQuery,
|
proc tryInsertID*(db: DbConn, query: SqlQuery,
|
||||||
args: varargs[string, `$`]): int64
|
args: varargs[string, `$`]): int64
|
||||||
{.tags: [FWriteDb], raises: [].} =
|
{.tags: [FWriteDb], raises: [].} =
|
||||||
## executes the query (typically "INSERT") and returns the
|
## executes the query (typically "INSERT") and returns the
|
||||||
|
|
@ -162,7 +163,7 @@ proc tryInsertID*(db: TDbConn, query: TSqlQuery,
|
||||||
if finalize(stmt) != SQLITE_OK:
|
if finalize(stmt) != SQLITE_OK:
|
||||||
result = -1
|
result = -1
|
||||||
|
|
||||||
proc insertID*(db: TDbConn, query: TSqlQuery,
|
proc insertID*(db: DbConn, query: SqlQuery,
|
||||||
args: varargs[string, `$`]): int64 {.tags: [FWriteDb].} =
|
args: varargs[string, `$`]): int64 {.tags: [FWriteDb].} =
|
||||||
## executes the query (typically "INSERT") and returns the
|
## executes the query (typically "INSERT") and returns the
|
||||||
## generated ID for the row. For Postgre this adds
|
## generated ID for the row. For Postgre this adds
|
||||||
|
|
@ -171,7 +172,7 @@ proc insertID*(db: TDbConn, query: TSqlQuery,
|
||||||
result = tryInsertID(db, query, args)
|
result = tryInsertID(db, query, args)
|
||||||
if result < 0: dbError(db)
|
if result < 0: dbError(db)
|
||||||
|
|
||||||
proc execAffectedRows*(db: TDbConn, query: TSqlQuery,
|
proc execAffectedRows*(db: DbConn, query: SqlQuery,
|
||||||
args: varargs[string, `$`]): int64 {.
|
args: varargs[string, `$`]): int64 {.
|
||||||
tags: [FReadDb, FWriteDb].} =
|
tags: [FReadDb, FWriteDb].} =
|
||||||
## executes the query (typically "UPDATE") and returns the
|
## executes the query (typically "UPDATE") and returns the
|
||||||
|
|
@ -179,21 +180,21 @@ proc execAffectedRows*(db: TDbConn, query: TSqlQuery,
|
||||||
exec(db, query, args)
|
exec(db, query, args)
|
||||||
result = changes(db)
|
result = changes(db)
|
||||||
|
|
||||||
proc close*(db: TDbConn) {.tags: [FDb].} =
|
proc close*(db: DbConn) {.tags: [FDb].} =
|
||||||
## closes the database connection.
|
## closes the database connection.
|
||||||
if sqlite3.close(db) != SQLITE_OK: dbError(db)
|
if sqlite3.close(db) != SQLITE_OK: dbError(db)
|
||||||
|
|
||||||
proc open*(connection, user, password, database: string): TDbConn {.
|
proc open*(connection, user, password, database: string): DbConn {.
|
||||||
tags: [FDb].} =
|
tags: [FDb].} =
|
||||||
## opens a database connection. Raises `EDb` if the connection could not
|
## opens a database connection. Raises `EDb` if the connection could not
|
||||||
## be established. Only the ``connection`` parameter is used for ``sqlite``.
|
## be established. Only the ``connection`` parameter is used for ``sqlite``.
|
||||||
var db: TDbConn
|
var db: DbConn
|
||||||
if sqlite3.open(connection, db) == SQLITE_OK:
|
if sqlite3.open(connection, db) == SQLITE_OK:
|
||||||
result = db
|
result = db
|
||||||
else:
|
else:
|
||||||
dbError(db)
|
dbError(db)
|
||||||
|
|
||||||
proc setEncoding*(connection: TDbConn, encoding: string): bool {.
|
proc setEncoding*(connection: DbConn, encoding: string): bool {.
|
||||||
tags: [FDb].} =
|
tags: [FDb].} =
|
||||||
## sets the encoding of a database connection, returns true for
|
## sets the encoding of a database connection, returns true for
|
||||||
## success, false for failure.
|
## success, false for failure.
|
||||||
|
|
|
||||||
|
|
@ -17,23 +17,24 @@ from sdl import PSurface # Bug
|
||||||
from sdl_ttf import openFont, closeFont
|
from sdl_ttf import openFont, closeFont
|
||||||
|
|
||||||
type
|
type
|
||||||
TRect* = tuple[x, y, width, height: int]
|
Rect* = tuple[x, y, width, height: int]
|
||||||
TPoint* = tuple[x, y: int]
|
Point* = tuple[x, y: int]
|
||||||
|
|
||||||
PSurface* = ref TSurface ## a surface to draw onto
|
PSurface* = ref Surface ## a surface to draw onto
|
||||||
TSurface* {.pure, final.} = object
|
Surface* {.pure, final.} = object
|
||||||
w*, h*: Natural
|
w*, h*: Natural
|
||||||
s*: sdl.PSurface
|
s*: sdl.PSurface
|
||||||
|
|
||||||
EGraphics* = object of IOError
|
EGraphics* = object of IOError
|
||||||
|
|
||||||
TFont {.pure, final.} = object
|
Font {.pure, final.} = object
|
||||||
f: sdl_ttf.PFont
|
f: sdl_ttf.PFont
|
||||||
color: sdl.TColor
|
color: sdl.Color
|
||||||
PFont* = ref TFont ## represents a font
|
PFont* = ref Font ## represents a font
|
||||||
|
{.deprecated: [TSurface: Surface, TFont: Font, TRect: Rect, TPoint: Point].}
|
||||||
|
|
||||||
proc toSdlColor*(c: Color): sdl.TColor =
|
proc toSdlColor*(c: Color): sdl.Color =
|
||||||
## Convert colors.TColor to sdl.TColor
|
## Convert colors.Color to sdl.Color
|
||||||
var x = c.extractRGB
|
var x = c.extractRGB
|
||||||
result.r = x.r and 0xff
|
result.r = x.r and 0xff
|
||||||
result.g = x.g and 0xff
|
result.g = x.g and 0xff
|
||||||
|
|
@ -45,8 +46,8 @@ proc createSdlColor*(sur: PSurface, c: Color, alpha: int = 0): int32 =
|
||||||
return sdl.mapRGBA(sur.s.format, x.r and 0xff, x.g and 0xff,
|
return sdl.mapRGBA(sur.s.format, x.r and 0xff, x.g and 0xff,
|
||||||
x.b and 0xff, alpha and 0xff)
|
x.b and 0xff, alpha and 0xff)
|
||||||
|
|
||||||
proc toSdlRect*(r: TRect): sdl.TRect =
|
proc toSdlRect*(r: Rect): sdl.Rect =
|
||||||
## Convert ``graphics.TRect`` to ``sdl.TRect``.
|
## Convert ``graphics.Rect`` to ``sdl.Rect``.
|
||||||
result.x = int16(r.x)
|
result.x = int16(r.x)
|
||||||
result.y = int16(r.y)
|
result.y = int16(r.y)
|
||||||
result.w = uint16(r.width)
|
result.w = uint16(r.width)
|
||||||
|
|
@ -103,8 +104,9 @@ proc writeToBMP*(sur: PSurface, filename: string) =
|
||||||
raise newException(IOError, "cannot write: " & filename)
|
raise newException(IOError, "cannot write: " & filename)
|
||||||
|
|
||||||
type
|
type
|
||||||
TPixels = array[0..1000_000-1, int32]
|
Pixels = array[0..1000_000-1, int32]
|
||||||
PPixels = ptr TPixels
|
PPixels = ptr Pixels
|
||||||
|
{.deprecated: [TPixels: Pixels].}
|
||||||
|
|
||||||
template setPix(video, pitch, x, y, col: expr): stmt =
|
template setPix(video, pitch, x, y, col: expr): stmt =
|
||||||
video[y * pitch + x] = int32(col)
|
video[y * pitch + x] = int32(col)
|
||||||
|
|
@ -128,7 +130,7 @@ proc setPixel(sur: PSurface, x, y: Natural, col: colors.Color) {.inline.} =
|
||||||
#pixs[y * (sur.s.pitch div colSize) + x] = int(col)
|
#pixs[y * (sur.s.pitch div colSize) + x] = int(col)
|
||||||
setPix(pixs, sur.s.pitch.int div ColSize, x, y, col)
|
setPix(pixs, sur.s.pitch.int div ColSize, x, y, col)
|
||||||
|
|
||||||
proc `[]`*(sur: PSurface, p: TPoint): Color =
|
proc `[]`*(sur: PSurface, p: Point): Color =
|
||||||
## get pixel at position `p`. No range checking is done!
|
## get pixel at position `p`. No range checking is done!
|
||||||
result = getPixel(sur, p.x, p.y)
|
result = getPixel(sur, p.x, p.y)
|
||||||
|
|
||||||
|
|
@ -136,7 +138,7 @@ proc `[]`*(sur: PSurface, x, y: int): Color =
|
||||||
## get pixel at position ``(x, y)``. No range checking is done!
|
## get pixel at position ``(x, y)``. No range checking is done!
|
||||||
result = getPixel(sur, x, y)
|
result = getPixel(sur, x, y)
|
||||||
|
|
||||||
proc `[]=`*(sur: PSurface, p: TPoint, col: Color) =
|
proc `[]=`*(sur: PSurface, p: Point, col: Color) =
|
||||||
## set the pixel at position `p`. No range checking is done!
|
## set the pixel at position `p`. No range checking is done!
|
||||||
setPixel(sur, p.x, p.y, col)
|
setPixel(sur, p.x, p.y, col)
|
||||||
|
|
||||||
|
|
@ -144,10 +146,10 @@ proc `[]=`*(sur: PSurface, x, y: int, col: Color) =
|
||||||
## set the pixel at position ``(x, y)``. No range checking is done!
|
## set the pixel at position ``(x, y)``. No range checking is done!
|
||||||
setPixel(sur, x, y, col)
|
setPixel(sur, x, y, col)
|
||||||
|
|
||||||
proc blit*(destSurf: PSurface, destRect: TRect, srcSurf: PSurface,
|
proc blit*(destSurf: PSurface, destRect: Rect, srcSurf: PSurface,
|
||||||
srcRect: TRect) =
|
srcRect: Rect) =
|
||||||
## Copies ``srcSurf`` into ``destSurf``
|
## Copies ``srcSurf`` into ``destSurf``
|
||||||
var destTRect, srcTRect: sdl.TRect
|
var destTRect, srcTRect: sdl.Rect
|
||||||
|
|
||||||
destTRect.x = int16(destRect.x)
|
destTRect.x = int16(destRect.x)
|
||||||
destTRect.y = int16(destRect.y)
|
destTRect.y = int16(destRect.y)
|
||||||
|
|
@ -168,7 +170,7 @@ proc textBounds*(text: string, font = defaultFont): tuple[width, height: int] =
|
||||||
result.width = int(w)
|
result.width = int(w)
|
||||||
result.height = int(h)
|
result.height = int(h)
|
||||||
|
|
||||||
proc drawText*(sur: PSurface, p: TPoint, text: string, font = defaultFont) =
|
proc drawText*(sur: PSurface, p: Point, text: string, font = defaultFont) =
|
||||||
## Draws text with a transparent background, at location ``p`` with the given
|
## Draws text with a transparent background, at location ``p`` with the given
|
||||||
## font.
|
## font.
|
||||||
var textSur: PSurface # This surface will have the text drawn on it
|
var textSur: PSurface # This surface will have the text drawn on it
|
||||||
|
|
@ -179,7 +181,7 @@ proc drawText*(sur: PSurface, p: TPoint, text: string, font = defaultFont) =
|
||||||
# Merge the text surface with sur
|
# Merge the text surface with sur
|
||||||
sur.blit((p.x, p.y, sur.w, sur.h), textSur, (0, 0, sur.w, sur.h))
|
sur.blit((p.x, p.y, sur.w, sur.h), textSur, (0, 0, sur.w, sur.h))
|
||||||
|
|
||||||
proc drawText*(sur: PSurface, p: TPoint, text: string,
|
proc drawText*(sur: PSurface, p: Point, text: string,
|
||||||
bg: Color, font = defaultFont) =
|
bg: Color, font = defaultFont) =
|
||||||
## Draws text, at location ``p`` with font ``font``. ``bg``
|
## Draws text, at location ``p`` with font ``font``. ``bg``
|
||||||
## is the background color.
|
## is the background color.
|
||||||
|
|
@ -189,7 +191,7 @@ proc drawText*(sur: PSurface, p: TPoint, text: string,
|
||||||
# Merge the text surface with sur
|
# Merge the text surface with sur
|
||||||
sur.blit((p.x, p.y, sur.w, sur.h), textSur, (0, 0, sur.w, sur.h))
|
sur.blit((p.x, p.y, sur.w, sur.h), textSur, (0, 0, sur.w, sur.h))
|
||||||
|
|
||||||
proc drawCircle*(sur: PSurface, p: TPoint, r: Natural, color: Color) =
|
proc drawCircle*(sur: PSurface, p: Point, r: Natural, color: Color) =
|
||||||
## draws a circle with center `p` and radius `r` with the given color
|
## draws a circle with center `p` and radius `r` with the given color
|
||||||
## onto the surface `sur`.
|
## onto the surface `sur`.
|
||||||
var video = cast[PPixels](sur.s.pixels)
|
var video = cast[PPixels](sur.s.pixels)
|
||||||
|
|
@ -229,7 +231,7 @@ proc `>-<`(val: int, s: PSurface): int {.inline.} =
|
||||||
proc `>|<`(val: int, s: PSurface): int {.inline.} =
|
proc `>|<`(val: int, s: PSurface): int {.inline.} =
|
||||||
return if val < 0: 0 elif val >= s.h: s.h-1 else: val
|
return if val < 0: 0 elif val >= s.h: s.h-1 else: val
|
||||||
|
|
||||||
proc drawLine*(sur: PSurface, p1, p2: TPoint, color: Color) =
|
proc drawLine*(sur: PSurface, p1, p2: Point, color: Color) =
|
||||||
## draws a line between the two points `p1` and `p2` with the given color
|
## draws a line between the two points `p1` and `p2` with the given color
|
||||||
## onto the surface `sur`.
|
## onto the surface `sur`.
|
||||||
var stepx, stepy: int = 0
|
var stepx, stepy: int = 0
|
||||||
|
|
@ -291,7 +293,7 @@ proc drawVerLine*(sur: PSurface, x, y, h: Natural, color: Color) =
|
||||||
for i in 0 .. min(sur.s.h-y, h)-1:
|
for i in 0 .. min(sur.s.h-y, h)-1:
|
||||||
setPix(video, pitch, x, y + i, color)
|
setPix(video, pitch, x, y + i, color)
|
||||||
|
|
||||||
proc fillCircle*(s: PSurface, p: TPoint, r: Natural, color: Color) =
|
proc fillCircle*(s: PSurface, p: Point, r: Natural, color: Color) =
|
||||||
## draws a circle with center `p` and radius `r` with the given color
|
## draws a circle with center `p` and radius `r` with the given color
|
||||||
## onto the surface `sur` and fills it.
|
## onto the surface `sur` and fills it.
|
||||||
var a = 1 - r
|
var a = 1 - r
|
||||||
|
|
@ -319,7 +321,7 @@ proc fillCircle*(s: PSurface, p: TPoint, r: Natural, color: Color) =
|
||||||
drawVerLine(s, x - py - 1, y - px, px, color)
|
drawVerLine(s, x - py - 1, y - px, px, color)
|
||||||
px = px + 1
|
px = px + 1
|
||||||
|
|
||||||
proc drawRect*(sur: PSurface, r: TRect, color: Color) =
|
proc drawRect*(sur: PSurface, r: Rect, color: Color) =
|
||||||
## draws a rectangle.
|
## draws a rectangle.
|
||||||
var video = cast[PPixels](sur.s.pixels)
|
var video = cast[PPixels](sur.s.pixels)
|
||||||
var pitch = sur.s.pitch.int div ColSize
|
var pitch = sur.s.pitch.int div ColSize
|
||||||
|
|
@ -337,7 +339,7 @@ proc drawRect*(sur: PSurface, r: TRect, color: Color) =
|
||||||
setPix(video, pitch, r.x, r.y + i, color)
|
setPix(video, pitch, r.x, r.y + i, color)
|
||||||
setPix(video, pitch, r.x + minW - 1, r.y + i, color) # Draw right side
|
setPix(video, pitch, r.x + minW - 1, r.y + i, color) # Draw right side
|
||||||
|
|
||||||
proc fillRect*(sur: PSurface, r: TRect, col: Color) =
|
proc fillRect*(sur: PSurface, r: Rect, col: Color) =
|
||||||
## Fills a rectangle using sdl's ``FillRect`` function.
|
## Fills a rectangle using sdl's ``FillRect`` function.
|
||||||
var rect = toSdlRect(r)
|
var rect = toSdlRect(r)
|
||||||
if sdl.fillRect(sur.s, addr(rect), sur.createSdlColor(col)) == -1:
|
if sdl.fillRect(sur.s, addr(rect), sur.createSdlColor(col)) == -1:
|
||||||
|
|
@ -424,7 +426,7 @@ template cround(x: expr): expr = ipart(x + 0.5)
|
||||||
template fpart(x: expr): expr = x - ipart(x)
|
template fpart(x: expr): expr = x - ipart(x)
|
||||||
template rfpart(x: expr): expr = 1.0 - fpart(x)
|
template rfpart(x: expr): expr = 1.0 - fpart(x)
|
||||||
|
|
||||||
proc drawLineAA*(sur: PSurface, p1, p2: TPoint, color: Color) =
|
proc drawLineAA*(sur: PSurface, p1, p2: Point, color: Color) =
|
||||||
## Draws a anti-aliased line from ``p1`` to ``p2``, using Xiaolin Wu's
|
## Draws a anti-aliased line from ``p1`` to ``p2``, using Xiaolin Wu's
|
||||||
## line algorithm
|
## line algorithm
|
||||||
var (x1, x2, y1, y2) = (p1.x.toFloat(), p2.x.toFloat(),
|
var (x1, x2, y1, y2) = (p1.x.toFloat(), p2.x.toFloat(),
|
||||||
|
|
@ -490,9 +492,9 @@ proc fillSurface*(sur: PSurface, color: Color) =
|
||||||
template withEvents*(surf: PSurface, event: expr, actions: stmt): stmt {.
|
template withEvents*(surf: PSurface, event: expr, actions: stmt): stmt {.
|
||||||
immediate.} =
|
immediate.} =
|
||||||
## Simple template which creates an event loop. ``Event`` is the name of the
|
## Simple template which creates an event loop. ``Event`` is the name of the
|
||||||
## variable containing the TEvent object.
|
## variable containing the Event object.
|
||||||
while true:
|
while true:
|
||||||
var event: sdl.TEvent
|
var event: sdl.Event
|
||||||
if sdl.waitEvent(addr(event)) == 1:
|
if sdl.waitEvent(addr(event)) == 1:
|
||||||
actions
|
actions
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -135,7 +135,7 @@ else:
|
||||||
var cur, old: Termios
|
var cur, old: Termios
|
||||||
discard fd.tcgetattr(cur.addr)
|
discard fd.tcgetattr(cur.addr)
|
||||||
old = cur
|
old = cur
|
||||||
cur.c_lflag = cur.c_lflag and not Tcflag(ECHO)
|
cur.c_lflag = cur.c_lflag and not Cflag(ECHO)
|
||||||
discard fd.tcsetattr(TCSADRAIN, cur.addr)
|
discard fd.tcsetattr(TCSADRAIN, cur.addr)
|
||||||
stdout.write prompt
|
stdout.write prompt
|
||||||
result = stdin.readLine(password)
|
result = stdin.readLine(password)
|
||||||
|
|
|
||||||
|
|
@ -15,11 +15,12 @@
|
||||||
import openssl, strutils, os
|
import openssl, strutils, os
|
||||||
|
|
||||||
type
|
type
|
||||||
TSecureSocket* = object
|
SecureSocket* = object
|
||||||
ssl: SslPtr
|
ssl: SslPtr
|
||||||
bio: BIO
|
bio: BIO
|
||||||
|
{.deprecated: [TSecureSocket: SecureSocket].}
|
||||||
|
|
||||||
proc connect*(sock: var TSecureSocket, address: string,
|
proc connect*(sock: var SecureSocket, address: string,
|
||||||
port: int): int =
|
port: int): int =
|
||||||
## Connects to the specified `address` on the specified `port`.
|
## Connects to the specified `address` on the specified `port`.
|
||||||
## Returns the result of the certificate validation.
|
## Returns the result of the certificate validation.
|
||||||
|
|
@ -52,7 +53,7 @@ proc connect*(sock: var TSecureSocket, address: string,
|
||||||
|
|
||||||
result = SSL_get_verify_result(sock.ssl)
|
result = SSL_get_verify_result(sock.ssl)
|
||||||
|
|
||||||
proc recvLine*(sock: TSecureSocket, line: var TaintedString): bool =
|
proc recvLine*(sock: SecureSocket, line: var TaintedString): bool =
|
||||||
## Acts in a similar fashion to the `recvLine` in the sockets module.
|
## Acts in a similar fashion to the `recvLine` in the sockets module.
|
||||||
## Returns false when no data is available to be read.
|
## Returns false when no data is available to be read.
|
||||||
## `Line` must be initialized and not nil!
|
## `Line` must be initialized and not nil!
|
||||||
|
|
@ -71,19 +72,19 @@ proc recvLine*(sock: TSecureSocket, line: var TaintedString): bool =
|
||||||
add(line.string, c)
|
add(line.string, c)
|
||||||
|
|
||||||
|
|
||||||
proc send*(sock: TSecureSocket, data: string) =
|
proc send*(sock: SecureSocket, data: string) =
|
||||||
## Writes `data` to the socket.
|
## Writes `data` to the socket.
|
||||||
if BIO_write(sock.bio, data, data.len.cint) <= 0:
|
if BIO_write(sock.bio, data, data.len.cint) <= 0:
|
||||||
raiseOSError(osLastError())
|
raiseOSError(osLastError())
|
||||||
|
|
||||||
proc close*(sock: TSecureSocket) =
|
proc close*(sock: SecureSocket) =
|
||||||
## Closes the socket
|
## Closes the socket
|
||||||
if BIO_free(sock.bio) <= 0:
|
if BIO_free(sock.bio) <= 0:
|
||||||
ERR_print_errors_fp(stderr)
|
ERR_print_errors_fp(stderr)
|
||||||
raiseOSError(osLastError())
|
raiseOSError(osLastError())
|
||||||
|
|
||||||
when not defined(testing) and isMainModule:
|
when not defined(testing) and isMainModule:
|
||||||
var s: TSecureSocket
|
var s: SecureSocket
|
||||||
echo connect(s, "smtp.gmail.com", 465)
|
echo connect(s, "smtp.gmail.com", 465)
|
||||||
|
|
||||||
#var buffer: array[0..255, char]
|
#var buffer: array[0..255, char]
|
||||||
|
|
|
||||||
|
|
@ -13,18 +13,18 @@ import
|
||||||
streams, libzip, times, os, strutils
|
streams, libzip, times, os, strutils
|
||||||
|
|
||||||
type
|
type
|
||||||
TZipArchive* = object of RootObj ## represents a zip archive
|
ZipArchive* = object of RootObj ## represents a zip archive
|
||||||
mode: FileMode
|
mode: FileMode
|
||||||
w: PZip
|
w: PZip
|
||||||
|
{.deprecated: [TZipArchive: ZipArchive].}
|
||||||
|
|
||||||
|
proc zipError(z: var ZipArchive) =
|
||||||
proc zipError(z: var TZipArchive) =
|
|
||||||
var e: ref IOError
|
var e: ref IOError
|
||||||
new(e)
|
new(e)
|
||||||
e.msg = $zip_strerror(z.w)
|
e.msg = $zip_strerror(z.w)
|
||||||
raise e
|
raise e
|
||||||
|
|
||||||
proc open*(z: var TZipArchive, filename: string, mode: FileMode = fmRead): bool =
|
proc open*(z: var ZipArchive, filename: string, mode: FileMode = fmRead): bool =
|
||||||
## Opens a zip file for reading, writing or appending. All file modes are
|
## Opens a zip file for reading, writing or appending. All file modes are
|
||||||
## supported. Returns true iff successful, false otherwise.
|
## supported. Returns true iff successful, false otherwise.
|
||||||
var err, flags: int32
|
var err, flags: int32
|
||||||
|
|
@ -38,11 +38,11 @@ proc open*(z: var TZipArchive, filename: string, mode: FileMode = fmRead): bool
|
||||||
z.mode = mode
|
z.mode = mode
|
||||||
result = z.w != nil
|
result = z.w != nil
|
||||||
|
|
||||||
proc close*(z: var TZipArchive) =
|
proc close*(z: var ZipArchive) =
|
||||||
## Closes a zip file.
|
## Closes a zip file.
|
||||||
zip_close(z.w)
|
zip_close(z.w)
|
||||||
|
|
||||||
proc createDir*(z: var TZipArchive, dir: string) =
|
proc createDir*(z: var ZipArchive, dir: string) =
|
||||||
## Creates a directory within the `z` archive. This does not fail if the
|
## Creates a directory within the `z` archive. This does not fail if the
|
||||||
## directory already exists. Note that for adding a file like
|
## directory already exists. Note that for adding a file like
|
||||||
## ``"path1/path2/filename"`` it is not necessary
|
## ``"path1/path2/filename"`` it is not necessary
|
||||||
|
|
@ -52,7 +52,7 @@ proc createDir*(z: var TZipArchive, dir: string) =
|
||||||
discard zip_add_dir(z.w, dir)
|
discard zip_add_dir(z.w, dir)
|
||||||
zip_error_clear(z.w)
|
zip_error_clear(z.w)
|
||||||
|
|
||||||
proc addFile*(z: var TZipArchive, dest, src: string) =
|
proc addFile*(z: var ZipArchive, dest, src: string) =
|
||||||
## Adds the file `src` to the archive `z` with the name `dest`. `dest`
|
## Adds the file `src` to the archive `z` with the name `dest`. `dest`
|
||||||
## may contain a path that will be created.
|
## may contain a path that will be created.
|
||||||
assert(z.mode != fmRead)
|
assert(z.mode != fmRead)
|
||||||
|
|
@ -67,13 +67,13 @@ proc addFile*(z: var TZipArchive, dest, src: string) =
|
||||||
zip_source_free(zipsrc)
|
zip_source_free(zipsrc)
|
||||||
zipError(z)
|
zipError(z)
|
||||||
|
|
||||||
proc addFile*(z: var TZipArchive, file: string) =
|
proc addFile*(z: var ZipArchive, file: string) =
|
||||||
## A shortcut for ``addFile(z, file, file)``, i.e. the name of the source is
|
## A shortcut for ``addFile(z, file, file)``, i.e. the name of the source is
|
||||||
## the name of the destination.
|
## the name of the destination.
|
||||||
addFile(z, file, file)
|
addFile(z, file, file)
|
||||||
|
|
||||||
proc mySourceCallback(state, data: pointer, len: int,
|
proc mySourceCallback(state, data: pointer, len: int,
|
||||||
cmd: TZipSourceCmd): int {.cdecl.} =
|
cmd: ZipSourceCmd): int {.cdecl.} =
|
||||||
var src = cast[Stream](state)
|
var src = cast[Stream](state)
|
||||||
case cmd
|
case cmd
|
||||||
of ZIP_SOURCE_OPEN:
|
of ZIP_SOURCE_OPEN:
|
||||||
|
|
@ -86,7 +86,7 @@ proc mySourceCallback(state, data: pointer, len: int,
|
||||||
zip_stat_init(stat)
|
zip_stat_init(stat)
|
||||||
stat.size = high(int32)-1 # we don't know the size
|
stat.size = high(int32)-1 # we don't know the size
|
||||||
stat.mtime = getTime()
|
stat.mtime = getTime()
|
||||||
result = sizeof(TZipStat)
|
result = sizeof(ZipStat)
|
||||||
of ZIP_SOURCE_ERROR:
|
of ZIP_SOURCE_ERROR:
|
||||||
var err = cast[ptr array[0..1, cint]](data)
|
var err = cast[ptr array[0..1, cint]](data)
|
||||||
err[0] = ZIP_ER_INTERNAL
|
err[0] = ZIP_ER_INTERNAL
|
||||||
|
|
@ -95,7 +95,7 @@ proc mySourceCallback(state, data: pointer, len: int,
|
||||||
of constZIP_SOURCE_FREE: GC_unref(src)
|
of constZIP_SOURCE_FREE: GC_unref(src)
|
||||||
else: assert(false)
|
else: assert(false)
|
||||||
|
|
||||||
proc addFile*(z: var TZipArchive, dest: string, src: Stream) =
|
proc addFile*(z: var ZipArchive, dest: string, src: Stream) =
|
||||||
## Adds a file named with `dest` to the archive `z`. `dest`
|
## Adds a file named with `dest` to the archive `z`. `dest`
|
||||||
## may contain a path. The file's content is read from the `src` stream.
|
## may contain a path. The file's content is read from the `src` stream.
|
||||||
assert(z.mode != fmRead)
|
assert(z.mode != fmRead)
|
||||||
|
|
@ -109,12 +109,13 @@ proc addFile*(z: var TZipArchive, dest: string, src: Stream) =
|
||||||
# -------------- zip file stream ---------------------------------------------
|
# -------------- zip file stream ---------------------------------------------
|
||||||
|
|
||||||
type
|
type
|
||||||
TZipFileStream = object of StreamObj
|
ZipFileStream = object of StreamObj
|
||||||
f: PZipFile
|
f: PZipFile
|
||||||
atEnd: bool
|
atEnd: bool
|
||||||
|
|
||||||
PZipFileStream* =
|
PZipFileStream* =
|
||||||
ref TZipFileStream ## a reader stream of a file within a zip archive
|
ref ZipFileStream ## a reader stream of a file within a zip archive
|
||||||
|
{.deprecated: [TZipFileStream: ZipFileStream].}
|
||||||
|
|
||||||
proc fsClose(s: Stream) = zip_fclose(PZipFileStream(s).f)
|
proc fsClose(s: Stream) = zip_fclose(PZipFileStream(s).f)
|
||||||
proc fsAtEnd(s: Stream): bool = PZipFileStream(s).atEnd
|
proc fsAtEnd(s: Stream): bool = PZipFileStream(s).atEnd
|
||||||
|
|
@ -134,7 +135,7 @@ proc newZipFileStream(f: PZipFile): PZipFileStream =
|
||||||
|
|
||||||
# ----------------------------------------------------------------------------
|
# ----------------------------------------------------------------------------
|
||||||
|
|
||||||
proc getStream*(z: var TZipArchive, filename: string): PZipFileStream =
|
proc getStream*(z: var ZipArchive, filename: string): PZipFileStream =
|
||||||
## returns a stream that can be used to read the file named `filename`
|
## returns a stream that can be used to read the file named `filename`
|
||||||
## from the archive `z`. Returns nil in case of an error.
|
## from the archive `z`. Returns nil in case of an error.
|
||||||
## The returned stream does not support the `setPosition`, `getPosition`,
|
## The returned stream does not support the `setPosition`, `getPosition`,
|
||||||
|
|
@ -142,7 +143,7 @@ proc getStream*(z: var TZipArchive, filename: string): PZipFileStream =
|
||||||
var x = zip_fopen(z.w, filename, 0'i32)
|
var x = zip_fopen(z.w, filename, 0'i32)
|
||||||
if x != nil: result = newZipFileStream(x)
|
if x != nil: result = newZipFileStream(x)
|
||||||
|
|
||||||
iterator walkFiles*(z: var TZipArchive): string =
|
iterator walkFiles*(z: var ZipArchive): string =
|
||||||
## walks over all files in the archive `z` and returns the filename
|
## walks over all files in the archive `z` and returns the filename
|
||||||
## (including the path).
|
## (including the path).
|
||||||
var i = 0'i32
|
var i = 0'i32
|
||||||
|
|
@ -152,7 +153,7 @@ iterator walkFiles*(z: var TZipArchive): string =
|
||||||
inc(i)
|
inc(i)
|
||||||
|
|
||||||
|
|
||||||
proc extractFile*(z: var TZipArchive, srcFile: string, dest: Stream) =
|
proc extractFile*(z: var ZipArchive, srcFile: string, dest: Stream) =
|
||||||
## extracts a file from the zip archive `z` to the destination stream.
|
## extracts a file from the zip archive `z` to the destination stream.
|
||||||
var strm = getStream(z, srcFile)
|
var strm = getStream(z, srcFile)
|
||||||
while true:
|
while true:
|
||||||
|
|
@ -162,13 +163,13 @@ proc extractFile*(z: var TZipArchive, srcFile: string, dest: Stream) =
|
||||||
dest.flush()
|
dest.flush()
|
||||||
strm.close()
|
strm.close()
|
||||||
|
|
||||||
proc extractFile*(z: var TZipArchive, srcFile: string, dest: string) =
|
proc extractFile*(z: var ZipArchive, srcFile: string, dest: string) =
|
||||||
## extracts a file from the zip archive `z` to the destination filename.
|
## extracts a file from the zip archive `z` to the destination filename.
|
||||||
var file = newFileStream(dest, fmWrite)
|
var file = newFileStream(dest, fmWrite)
|
||||||
extractFile(z, srcFile, file)
|
extractFile(z, srcFile, file)
|
||||||
file.close()
|
file.close()
|
||||||
|
|
||||||
proc extractAll*(z: var TZipArchive, dest: string) =
|
proc extractAll*(z: var ZipArchive, dest: string) =
|
||||||
## extracts all files from archive `z` to the destination directory.
|
## extracts all files from archive `z` to the destination directory.
|
||||||
for file in walkFiles(z):
|
for file in walkFiles(z):
|
||||||
if file.endsWith("/"):
|
if file.endsWith("/"):
|
||||||
|
|
@ -177,7 +178,7 @@ proc extractAll*(z: var TZipArchive, dest: string) =
|
||||||
extractFile(z, file, dest / file)
|
extractFile(z, file, dest / file)
|
||||||
|
|
||||||
when not defined(testing) and isMainModule:
|
when not defined(testing) and isMainModule:
|
||||||
var zip: TZipArchive
|
var zip: ZipArchive
|
||||||
if not zip.open("nim-0.11.0.zip"):
|
if not zip.open("nim-0.11.0.zip"):
|
||||||
raise newException(IOError, "opening zip failed")
|
raise newException(IOError, "opening zip failed")
|
||||||
zip.extractAll("test")
|
zip.extractAll("test")
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue