Markdown code blocks migration part 7 (#20547)

This commit is contained in:
Andrey Makarov 2022-10-12 17:13:43 +03:00 • committed by GitHub
commit 19ff746916
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
17 changed files with 426 additions and 411 deletions

View file

@ -26,8 +26,9 @@
## That is, using the `?` (question mark) to signify the place where a ## That is, using the `?` (question mark) to signify the place where a
## value should be placed. For example: ## value should be placed. For example:
## ##
## .. code-block:: Nim ## ```Nim
## sql"INSERT INTO myTable (colA, colB, colC) VALUES (?, ?, ?)" ## sql"INSERT INTO myTable (colA, colB, colC) VALUES (?, ?, ?)"
## ```
## ##
## ##
## Examples ## Examples
@ -36,57 +37,60 @@
## Opening a connection to a database ## Opening a connection to a database
## ---------------------------------- ## ----------------------------------
## ##
## .. code-block:: Nim ## ```Nim
## import std/db_odbc ## import std/db_odbc
## var db = open("localhost", "user", "password", "dbname") ## var db = open("localhost", "user", "password", "dbname")
## db.close() ## db.close()
## ```
## ##
## Creating a table ## Creating a table
## ---------------- ## ----------------
## ##
## .. code-block:: Nim ## ```Nim
## db.exec(sql"DROP TABLE IF EXISTS myTable") ## db.exec(sql"DROP TABLE IF EXISTS myTable")
## db.exec(sql("""CREATE TABLE myTable ( ## db.exec(sql("""CREATE TABLE myTable (
## id integer, ## id integer,
## name varchar(50) not null)""")) ## name varchar(50) not null)"""))
## ```
## ##
## Inserting data ## Inserting data
## -------------- ## --------------
## ##
## .. code-block:: Nim ## ```Nim
## db.exec(sql"INSERT INTO myTable (id, name) VALUES (0, ?)", ## db.exec(sql"INSERT INTO myTable (id, name) VALUES (0, ?)",
## "Andreas") ## "Andreas")
## ```
## ##
## Large example ## Large example
## ------------- ## -------------
## ##
## .. code-block:: Nim ## ```Nim
## import std/[db_odbc, math]
## ##
## import std/[db_odbc, math] ## var theDb = open("localhost", "nim", "nim", "test")
## ##
## var theDb = open("localhost", "nim", "nim", "test") ## theDb.exec(sql"Drop table if exists myTestTbl")
## theDb.exec(sql("create table myTestTbl (" &
## " Id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, " &
## " Name VARCHAR(50) NOT NULL, " &
## " i INT(11), " &
## " f DECIMAL(18,10))"))
## ##
## theDb.exec(sql"Drop table if exists myTestTbl") ## theDb.exec(sql"START TRANSACTION")
## theDb.exec(sql("create table myTestTbl (" & ## for i in 1..1000:
## " Id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, " & ## theDb.exec(sql"INSERT INTO myTestTbl (name,i,f) VALUES (?,?,?)",
## " Name VARCHAR(50) NOT NULL, " & ## "Item#" & $i, i, sqrt(i.float))
## " i INT(11), " & ## theDb.exec(sql"COMMIT")
## " f DECIMAL(18,10))"))
## ##
## theDb.exec(sql"START TRANSACTION") ## for x in theDb.fastRows(sql"select * from myTestTbl"):
## for i in 1..1000: ## echo x
## theDb.exec(sql"INSERT INTO myTestTbl (name,i,f) VALUES (?,?,?)",
## "Item#" & $i, i, sqrt(i.float))
## theDb.exec(sql"COMMIT")
## ##
## for x in theDb.fastRows(sql"select * from myTestTbl"): ## let id = theDb.tryInsertId(sql"INSERT INTO myTestTbl (name,i,f) VALUES (?,?,?)",
## echo x ## "Item#1001", 1001, sqrt(1001.0))
## echo "Inserted item: ", theDb.getValue(sql"SELECT name FROM myTestTbl WHERE id=?", id)
## ##
## let id = theDb.tryInsertId(sql"INSERT INTO myTestTbl (name,i,f) VALUES (?,?,?)", ## theDb.close()
## "Item#1001", 1001, sqrt(1001.0)) ## ```
## echo "Inserted item: ", theDb.getValue(sql"SELECT name FROM myTestTbl WHERE id=?", id)
##
## theDb.close()
import strutils, odbcsql import strutils, odbcsql
import db_common import db_common

View file

@ -20,8 +20,9 @@
## That is, using the `?` (question mark) to signify the place where a ## That is, using the `?` (question mark) to signify the place where a
## value should be placed. For example: ## value should be placed. For example:
## ##
## .. code-block:: Nim ## ```Nim
## sql"INSERT INTO myTable (colA, colB, colC) VALUES (?, ?, ?)" ## sql"INSERT INTO myTable (colA, colB, colC) VALUES (?, ?, ?)"
## ```
## ##
## **Note**: There are two approaches to parameter substitution support by ## **Note**: There are two approaches to parameter substitution support by
## this module. ## this module.
@ -30,12 +31,13 @@
## ##
## 2. `SqlPrepared` using `$1, $2, $3, ...` ## 2. `SqlPrepared` using `$1, $2, $3, ...`
## ##
## .. code-block:: Nim ## ```Nim
## prepare(db, "myExampleInsert", ## prepare(db, "myExampleInsert",
## sql"""INSERT INTO myTable ## sql"""INSERT INTO myTable
## (colA, colB, colC) ## (colA, colB, colC)
## VALUES ($1, $2, $3)""", ## VALUES ($1, $2, $3)""",
## 3) ## 3)
## ```
## ##
## ##
## Unix Socket ## Unix Socket
@ -46,11 +48,12 @@
## ##
## To use Unix sockets with `db_postgres`, change the server address to the socket file path: ## To use Unix sockets with `db_postgres`, change the server address to the socket file path:
## ##
## .. code-block:: Nim ## ```Nim
## import std/db_postgres ## Change "localhost" or "127.0.0.1" to the socket file path ## import std/db_postgres ## Change "localhost" or "127.0.0.1" to the socket file path
## let db = db_postgres.open("/run/postgresql", "user", "password", "database") ## let db = db_postgres.open("/run/postgresql", "user", "password", "database")
## echo db.getAllRows(sql"SELECT version();") ## echo db.getAllRows(sql"SELECT version();")
## db.close() ## db.close()
## ```
## ##
## The socket file path is operating system specific and distribution specific, ## The socket file path is operating system specific and distribution specific,
## additional configuration may or may not be needed on your `postgresql.conf`. ## additional configuration may or may not be needed on your `postgresql.conf`.
@ -63,26 +66,29 @@
## Opening a connection to a database ## Opening a connection to a database
## ---------------------------------- ## ----------------------------------
## ##
## .. code-block:: Nim ## ```Nim
## import std/db_postgres ## import std/db_postgres
## let db = open("localhost", "user", "password", "dbname") ## let db = open("localhost", "user", "password", "dbname")
## db.close() ## db.close()
## ```
## ##
## Creating a table ## Creating a table
## ---------------- ## ----------------
## ##
## .. code-block:: Nim ## ```Nim
## db.exec(sql"DROP TABLE IF EXISTS myTable") ## db.exec(sql"DROP TABLE IF EXISTS myTable")
## db.exec(sql("""CREATE TABLE myTable ( ## db.exec(sql("""CREATE TABLE myTable (
## id integer, ## id integer,
## name varchar(50) not null)""")) ## name varchar(50) not null)"""))
## ```
## ##
## Inserting data ## Inserting data
## -------------- ## --------------
## ##
## .. code-block:: Nim ## ```Nim
## db.exec(sql"INSERT INTO myTable (id, name) VALUES (0, ?)", ## db.exec(sql"INSERT INTO myTable (id, name) VALUES (0, ?)",
## "Dominik") ## "Dominik")
## ```
import strutils, postgres import strutils, postgres
import db_common import db_common
@ -609,10 +615,9 @@ proc open*(connection, user, password, database: string): DbConn {.
## connect. ## connect.
## ##
## Example: ## Example:
## ## ```nim
## .. code-block:: nim ## con = open("", "", "", "host=localhost port=5432 dbname=mydb")
## ## ```
## con = open("", "", "", "host=localhost port=5432 dbname=mydb")
## ##
## See http://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING ## See http://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING
## for more information. ## for more information.

View file

@ -26,79 +26,78 @@
## That is, using the `?` (question mark) to signify the place where a ## That is, using the `?` (question mark) to signify the place where a
## value should be placed. For example: ## value should be placed. For example:
## ##
## .. code-block:: Nim ## ```Nim
## ## sql"INSERT INTO my_table (colA, colB, colC) VALUES (?, ?, ?)"
## sql"INSERT INTO my_table (colA, colB, colC) VALUES (?, ?, ?)" ## ```
## ##
## Opening a connection to a database ## Opening a connection to a database
## ---------------------------------- ## ----------------------------------
## ##
## .. code-block:: Nim ## ```Nim
## import std/db_sqlite
## ##
## import std/db_sqlite ## # user, password, database name can be empty.
## ## # These params are not used on db_sqlite module.
## # user, password, database name can be empty. ## let db = open("mytest.db", "", "", "")
## # These params are not used on db_sqlite module. ## db.close()
## let db = open("mytest.db", "", "", "") ## ```
## db.close()
## ##
## Creating a table ## Creating a table
## ---------------- ## ----------------
## ##
## .. code-block:: Nim ## ```Nim
## ## db.exec(sql"DROP TABLE IF EXISTS my_table")
## db.exec(sql"DROP TABLE IF EXISTS my_table") ## db.exec(sql"""CREATE TABLE my_table (
## db.exec(sql"""CREATE TABLE my_table ( ## id INTEGER,
## id INTEGER, ## name VARCHAR(50) NOT NULL
## name VARCHAR(50) NOT NULL ## )""")
## )""") ## ```
## ##
## Inserting data ## Inserting data
## -------------- ## --------------
## ##
## .. code-block:: Nim ## ```Nim
## ## db.exec(sql"INSERT INTO my_table (id, name) VALUES (0, ?)",
## db.exec(sql"INSERT INTO my_table (id, name) VALUES (0, ?)", ## "Jack")
## "Jack") ## ```
## ##
## Larger example ## Larger example
## -------------- ## --------------
## ##
## .. code-block:: nim ## ```Nim
## import std/[db_sqlite, math]
## ##
## import std/[db_sqlite, math] ## let db = open("mytest.db", "", "", "")
## ##
## let db = open("mytest.db", "", "", "") ## db.exec(sql"DROP TABLE IF EXISTS my_table")
## db.exec(sql"""CREATE TABLE my_table (
## id INTEGER PRIMARY KEY,
## name VARCHAR(50) NOT NULL,
## i INT(11),
## f DECIMAL(18, 10)
## )""")
## ##
## db.exec(sql"DROP TABLE IF EXISTS my_table") ## db.exec(sql"BEGIN")
## db.exec(sql"""CREATE TABLE my_table ( ## for i in 1..1000:
## id INTEGER PRIMARY KEY, ## db.exec(sql"INSERT INTO my_table (name, i, f) VALUES (?, ?, ?)",
## name VARCHAR(50) NOT NULL, ## "Item#" & $i, i, sqrt(i.float))
## i INT(11), ## db.exec(sql"COMMIT")
## f DECIMAL(18, 10)
## )""")
## ##
## db.exec(sql"BEGIN") ## for x in db.fastRows(sql"SELECT * FROM my_table"):
## for i in 1..1000: ## echo x
## db.exec(sql"INSERT INTO my_table (name, i, f) VALUES (?, ?, ?)",
## "Item#" & $i, i, sqrt(i.float))
## db.exec(sql"COMMIT")
## ##
## for x in db.fastRows(sql"SELECT * FROM my_table"): ## let id = db.tryInsertId(sql"""INSERT INTO my_table (name, i, f)
## echo x ## VALUES (?, ?, ?)""",
## "Item#1001", 1001, sqrt(1001.0))
## echo "Inserted item: ", db.getValue(sql"SELECT name FROM my_table WHERE id=?", id)
## ##
## let id = db.tryInsertId(sql"""INSERT INTO my_table (name, i, f) ## db.close()
## VALUES (?, ?, ?)""", ## ```
## "Item#1001", 1001, sqrt(1001.0))
## echo "Inserted item: ", db.getValue(sql"SELECT name FROM my_table WHERE id=?", id)
##
## db.close()
## ##
## Storing binary data example ## Storing binary data example
##---------------------------- ##----------------------------
## ##
## .. code-block:: nim ## ```nim
##
## import std/random ## import std/random
## ##
## ## Generate random float datas ## ## Generate random float datas
@ -144,6 +143,7 @@
## doAssert res == orig ## doAssert res == orig
## ##
## db.close() ## db.close()
## ```
## ##
## ##
## Note ## Note
@ -187,13 +187,12 @@ proc dbError*(db: DbConn) {.noreturn.} =
## Raises a `DbError` exception. ## Raises a `DbError` exception.
## ##
## **Examples:** ## **Examples:**
## ## ```Nim
## .. code-block:: Nim ## let db = open("mytest.db", "", "", "")
## ## if not db.tryExec(sql"SELECT * FROM not_exist_table"):
## let db = open("mytest.db", "", "", "") ## dbError(db)
## if not db.tryExec(sql"SELECT * FROM not_exist_table"): ## db.close()
## dbError(db) ## ```
## db.close()
var e: ref DbError var e: ref DbError
new(e) new(e)
e.msg = $sqlite3.errmsg(db) e.msg = $sqlite3.errmsg(db)
@ -227,13 +226,12 @@ proc tryExec*(db: DbConn, query: SqlQuery,
## Tries to execute the query and returns `true` if successful, `false` otherwise. ## Tries to execute the query and returns `true` if successful, `false` otherwise.
## ##
## **Examples:** ## **Examples:**
## ## ```Nim
## .. code-block:: Nim ## let db = open("mytest.db", "", "", "")
## ## if not db.tryExec(sql"SELECT * FROM my_table"):
## let db = open("mytest.db", "", "", "") ## dbError(db)
## if not db.tryExec(sql"SELECT * FROM my_table"): ## db.close()
## dbError(db) ## ```
## db.close()
assert(not db.isNil, "Database not connected.") assert(not db.isNil, "Database not connected.")
var q = dbFormat(query, args) var q = dbFormat(query, args)
var stmt: sqlite3.PStmt var stmt: sqlite3.PStmt
@ -259,17 +257,16 @@ proc exec*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]) {.
## Executes the query and raises a `DbError` exception if not successful. ## Executes the query and raises a `DbError` exception if not successful.
## ##
## **Examples:** ## **Examples:**
## ## ```Nim
## .. code-block:: Nim ## let db = open("mytest.db", "", "", "")
## ## try:
## let db = open("mytest.db", "", "", "") ## db.exec(sql"INSERT INTO my_table (id, name) VALUES (?, ?)",
## try: ## 1, "item#1")
## db.exec(sql"INSERT INTO my_table (id, name) VALUES (?, ?)", ## except:
## 1, "item#1") ## stderr.writeLine(getCurrentExceptionMsg())
## except: ## finally:
## stderr.writeLine(getCurrentExceptionMsg()) ## db.close()
## finally: ## ```
## db.close()
if not tryExec(db, query, args): dbError(db) if not tryExec(db, query, args): dbError(db)
proc newRow(L: int): Row = proc newRow(L: int): Row =
@ -310,24 +307,24 @@ iterator fastRows*(db: DbConn, query: SqlQuery,
## ##
## **Examples:** ## **Examples:**
## ##
## .. code-block:: Nim ## ```Nim
## let db = open("mytest.db", "", "", "")
## ##
## let db = open("mytest.db", "", "", "") ## # Records of my_table:
## # | id | name |
## # |----|----------|
## # | 1 | item#1 |
## # | 2 | item#2 |
## ##
## # Records of my_table: ## for row in db.fastRows(sql"SELECT id, name FROM my_table"):
## # | id | name | ## echo row
## # |----|----------|
## # | 1 | item#1 |
## # | 2 | item#2 |
## ##
## for row in db.fastRows(sql"SELECT id, name FROM my_table"): ## # Output:
## echo row ## # @["1", "item#1"]
## # @["2", "item#2"]
## ##
## # Output: ## db.close()
## # @["1", "item#1"] ## ```
## # @["2", "item#2"]
##
## db.close()
var stmt = setupQuery(db, query, args) var stmt = setupQuery(db, query, args)
var L = (column_count(stmt)) var L = (column_count(stmt))
var result = newRow(L) var result = newRow(L)
@ -359,8 +356,7 @@ iterator instantRows*(db: DbConn, query: SqlQuery,
## ##
## **Examples:** ## **Examples:**
## ##
## .. code-block:: Nim ## ```Nim
##
## let db = open("mytest.db", "", "", "") ## let db = open("mytest.db", "", "", "")
## ##
## # Records of my_table: ## # Records of my_table:
@ -383,6 +379,7 @@ iterator instantRows*(db: DbConn, query: SqlQuery,
## # length:2 ## # length:2
## ##
## db.close() ## db.close()
## ```
var stmt = setupQuery(db, query, args) var stmt = setupQuery(db, query, args)
try: try:
while step(stmt) == SQLITE_ROW: while step(stmt) == SQLITE_ROW:
@ -429,28 +426,28 @@ iterator instantRows*(db: DbConn; columns: var DbColumns; query: SqlQuery,
## ##
## **Examples:** ## **Examples:**
## ##
## .. code-block:: Nim ## ```Nim
## let db = open("mytest.db", "", "", "")
## ##
## let db = open("mytest.db", "", "", "") ## # Records of my_table:
## # | id | name |
## # |----|----------|
## # | 1 | item#1 |
## # | 2 | item#2 |
## ##
## # Records of my_table: ## var columns: DbColumns
## # | id | name | ## for row in db.instantRows(columns, sql"SELECT * FROM my_table"):
## # |----|----------| ## discard
## # | 1 | item#1 | ## echo columns[0]
## # | 2 | item#2 |
## ##
## var columns: DbColumns ## # Output:
## for row in db.instantRows(columns, sql"SELECT * FROM my_table"): ## # (name: "id", tableName: "my_table", typ: (kind: dbNull,
## discard ## # notNull: false, name: "INTEGER", size: 0, maxReprLen: 0, precision: 0,
## echo columns[0] ## # scale: 0, min: 0, max: 0, validValues: @[]), primaryKey: false,
## # foreignKey: false)
## ##
## # Output: ## db.close()
## # (name: "id", tableName: "my_table", typ: (kind: dbNull, ## ```
## # notNull: false, name: "INTEGER", size: 0, maxReprLen: 0, precision: 0,
## # scale: 0, min: 0, max: 0, validValues: @[]), primaryKey: false,
## # foreignKey: false)
##
## db.close()
var stmt = setupQuery(db, query, args) var stmt = setupQuery(db, query, args)
setColumns(columns, stmt) setColumns(columns, stmt)
try: try:
@ -490,28 +487,28 @@ proc getRow*(db: DbConn, query: SqlQuery,
## ##
## **Examples:** ## **Examples:**
## ##
## .. code-block:: Nim ## ```Nim
## let db = open("mytest.db", "", "", "")
## ##
## let db = open("mytest.db", "", "", "") ## # Records of my_table:
## # | id | name |
## # |----|----------|
## # | 1 | item#1 |
## # | 2 | item#2 |
## ##
## # Records of my_table: ## doAssert db.getRow(sql"SELECT id, name FROM my_table"
## # | id | name | ## ) == Row(@["1", "item#1"])
## # |----|----------| ## doAssert db.getRow(sql"SELECT id, name FROM my_table WHERE id = ?",
## # | 1 | item#1 | ## 2) == Row(@["2", "item#2"])
## # | 2 | item#2 |
## ##
## doAssert db.getRow(sql"SELECT id, name FROM my_table" ## # Returns empty.
## ) == Row(@["1", "item#1"]) ## doAssert db.getRow(sql"INSERT INTO my_table (id, name) VALUES (?, ?)",
## doAssert db.getRow(sql"SELECT id, name FROM my_table WHERE id = ?", ## 3, "item#3") == @[]
## 2) == Row(@["2", "item#2"]) ## doAssert db.getRow(sql"DELETE FROM my_table WHERE id = ?", 3) == @[]
## ## doAssert db.getRow(sql"UPDATE my_table SET name = 'ITEM#1' WHERE id = ?",
## # Returns empty. ## 1) == @[]
## doAssert db.getRow(sql"INSERT INTO my_table (id, name) VALUES (?, ?)", ## db.close()
## 3, "item#3") == @[] ## ```
## doAssert db.getRow(sql"DELETE FROM my_table WHERE id = ?", 3) == @[]
## doAssert db.getRow(sql"UPDATE my_table SET name = 'ITEM#1' WHERE id = ?",
## 1) == @[]
## db.close()
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)
@ -525,18 +522,18 @@ proc getAllRows*(db: DbConn, query: SqlQuery,
## ##
## **Examples:** ## **Examples:**
## ##
## .. code-block:: Nim ## ```Nim
## let db = open("mytest.db", "", "", "")
## ##
## let db = open("mytest.db", "", "", "") ## # Records of my_table:
## # | id | name |
## # |----|----------|
## # | 1 | item#1 |
## # | 2 | item#2 |
## ##
## # Records of my_table: ## doAssert db.getAllRows(sql"SELECT id, name FROM my_table") == @[Row(@["1", "item#1"]), Row(@["2", "item#2"])]
## # | id | name | ## db.close()
## # |----|----------| ## ```
## # | 1 | item#1 |
## # | 2 | item#2 |
##
## doAssert db.getAllRows(sql"SELECT id, name FROM my_table") == @[Row(@["1", "item#1"]), Row(@["2", "item#2"])]
## db.close()
result = @[] result = @[]
for r in fastRows(db, query, args): for r in fastRows(db, query, args):
result.add(r) result.add(r)
@ -554,24 +551,24 @@ iterator rows*(db: DbConn, query: SqlQuery,
## ##
## **Examples:** ## **Examples:**
## ##
## .. code-block:: Nim ## ```Nim
## let db = open("mytest.db", "", "", "")
## ##
## let db = open("mytest.db", "", "", "") ## # Records of my_table:
## # | id | name |
## # |----|----------|
## # | 1 | item#1 |
## # | 2 | item#2 |
## ##
## # Records of my_table: ## for row in db.rows(sql"SELECT id, name FROM my_table"):
## # | id | name | ## echo row
## # |----|----------|
## # | 1 | item#1 |
## # | 2 | item#2 |
## ##
## for row in db.rows(sql"SELECT id, name FROM my_table"): ## ## Output:
## echo row ## ## @["1", "item#1"]
## ## @["2", "item#2"]
## ##
## ## Output: ## db.close()
## ## @["1", "item#1"] ## ```
## ## @["2", "item#2"]
##
## db.close()
for r in fastRows(db, query, args): yield r for r in fastRows(db, query, args): yield r
iterator rows*(db: DbConn, stmtName: SqlPrepared): Row iterator rows*(db: DbConn, stmtName: SqlPrepared): Row
@ -586,22 +583,22 @@ proc getValue*(db: DbConn, query: SqlQuery,
## ##
## **Examples:** ## **Examples:**
## ##
## .. code-block:: Nim ## ```Nim
## let db = open("mytest.db", "", "", "")
## ##
## let db = open("mytest.db", "", "", "") ## # Records of my_table:
## # | id | name |
## # |----|----------|
## # | 1 | item#1 |
## # | 2 | item#2 |
## ##
## # Records of my_table: ## doAssert db.getValue(sql"SELECT name FROM my_table WHERE id = ?",
## # | id | name | ## 2) == "item#2"
## # |----|----------| ## doAssert db.getValue(sql"SELECT id, name FROM my_table") == "1"
## # | 1 | item#1 | ## doAssert db.getValue(sql"SELECT name, id FROM my_table") == "item#1"
## # | 2 | item#2 |
## ##
## doAssert db.getValue(sql"SELECT name FROM my_table WHERE id = ?", ## db.close()
## 2) == "item#2" ## ```
## doAssert db.getValue(sql"SELECT id, name FROM my_table") == "1"
## doAssert db.getValue(sql"SELECT name, id FROM my_table") == "item#1"
##
## db.close()
var stmt = setupQuery(db, query, args) var stmt = setupQuery(db, query, args)
if step(stmt) == SQLITE_ROW: if step(stmt) == SQLITE_ROW:
let cb = column_bytes(stmt, 0) let cb = column_bytes(stmt, 0)
@ -643,14 +640,14 @@ proc tryInsertID*(db: DbConn, query: SqlQuery,
## ##
## **Examples:** ## **Examples:**
## ##
## .. code-block:: Nim ## ```Nim
## let db = open("mytest.db", "", "", "")
## db.exec(sql"CREATE TABLE my_table (id INTEGER, name VARCHAR(50) NOT NULL)")
## ##
## let db = open("mytest.db", "", "", "") ## doAssert db.tryInsertID(sql"INSERT INTO not_exist_table (id, name) VALUES (?, ?)",
## db.exec(sql"CREATE TABLE my_table (id INTEGER, name VARCHAR(50) NOT NULL)") ## 1, "item#1") == -1
## ## db.close()
## doAssert db.tryInsertID(sql"INSERT INTO not_exist_table (id, name) VALUES (?, ?)", ## ```
## 1, "item#1") == -1
## db.close()
assert(not db.isNil, "Database not connected.") assert(not db.isNil, "Database not connected.")
var q = dbFormat(query, args) var q = dbFormat(query, args)
var stmt: sqlite3.PStmt var stmt: sqlite3.PStmt
@ -674,21 +671,21 @@ proc insertID*(db: DbConn, query: SqlQuery,
## ##
## **Examples:** ## **Examples:**
## ##
## .. code-block:: Nim ## ```Nim
## let db = open("mytest.db", "", "", "")
## db.exec(sql"CREATE TABLE my_table (id INTEGER, name VARCHAR(50) NOT NULL)")
## ##
## let db = open("mytest.db", "", "", "") ## for i in 0..2:
## db.exec(sql"CREATE TABLE my_table (id INTEGER, name VARCHAR(50) NOT NULL)") ## let id = db.insertID(sql"INSERT INTO my_table (id, name) VALUES (?, ?)", i, "item#" & $i)
## echo "LoopIndex = ", i, ", InsertID = ", id
## ##
## for i in 0..2: ## # Output:
## let id = db.insertID(sql"INSERT INTO my_table (id, name) VALUES (?, ?)", i, "item#" & $i) ## # LoopIndex = 0, InsertID = 1
## echo "LoopIndex = ", i, ", InsertID = ", id ## # LoopIndex = 1, InsertID = 2
## # LoopIndex = 2, InsertID = 3
## ##
## # Output: ## db.close()
## # LoopIndex = 0, InsertID = 1 ## ```
## # LoopIndex = 1, InsertID = 2
## # LoopIndex = 2, InsertID = 3
##
## db.close()
result = tryInsertID(db, query, args) result = tryInsertID(db, query, args)
if result < 0: dbError(db) if result < 0: dbError(db)
@ -713,19 +710,19 @@ proc execAffectedRows*(db: DbConn, query: SqlQuery,
## ##
## **Examples:** ## **Examples:**
## ##
## .. code-block:: Nim ## ```Nim
## let db = open("mytest.db", "", "", "")
## ##
## let db = open("mytest.db", "", "", "") ## # Records of my_table:
## # | id | name |
## # |----|----------|
## # | 1 | item#1 |
## # | 2 | item#2 |
## ##
## # Records of my_table: ## doAssert db.execAffectedRows(sql"UPDATE my_table SET name = 'TEST'") == 2
## # | id | name |
## # |----|----------|
## # | 1 | item#1 |
## # | 2 | item#2 |
## ##
## doAssert db.execAffectedRows(sql"UPDATE my_table SET name = 'TEST'") == 2 ## db.close()
## ## ```
## db.close()
exec(db, query, args) exec(db, query, args)
result = changes(db) result = changes(db)
@ -738,11 +735,10 @@ proc close*(db: DbConn) {.tags: [DbEffect].} =
## Closes the database connection. ## Closes the database connection.
## ##
## **Examples:** ## **Examples:**
## ## ```Nim
## .. code-block:: Nim ## let db = open("mytest.db", "", "", "")
## ## db.close()
## let db = open("mytest.db", "", "", "") ## ```
## db.close()
if sqlite3.close(db) != SQLITE_OK: dbError(db) if sqlite3.close(db) != SQLITE_OK: dbError(db)
proc open*(connection, user, password, database: string): DbConn {. proc open*(connection, user, password, database: string): DbConn {.
@ -753,16 +749,15 @@ proc open*(connection, user, password, database: string): DbConn {.
## **Note:** Only the `connection` parameter is used for `sqlite`. ## **Note:** Only the `connection` parameter is used for `sqlite`.
## ##
## **Examples:** ## **Examples:**
## ## ```Nim
## .. code-block:: Nim ## try:
## ## let db = open("mytest.db", "", "", "")
## try: ## ## do something...
## let db = open("mytest.db", "", "", "") ## ## db.getAllRows(sql"SELECT * FROM my_table")
## ## do something... ## db.close()
## ## db.getAllRows(sql"SELECT * FROM my_table") ## except:
## db.close() ## stderr.writeLine(getCurrentExceptionMsg())
## except: ## ```
## stderr.writeLine(getCurrentExceptionMsg())
var db: DbConn var db: DbConn
if sqlite3.open(connection, db) == SQLITE_OK: if sqlite3.open(connection, db) == SQLITE_OK:
result = db result = db

View file

@ -17,37 +17,42 @@
## ##
## This is roughly equivalent to the `async` keyword in JavaScript code. ## This is roughly equivalent to the `async` keyword in JavaScript code.
## ##
## .. code-block:: nim ## ```nim
## proc loadGame(name: string): Future[Game] {.async.} = ## proc loadGame(name: string): Future[Game] {.async.} =
## # code ## # code
## ```
## ##
## should be equivalent to ## should be equivalent to
## ##
## .. code-block:: javascript ## ```javascript
## async function loadGame(name) { ## async function loadGame(name) {
## // code ## // code
## } ## }
## ```
## ##
## A call to an asynchronous procedure usually needs `await` to wait for ## A call to an asynchronous procedure usually needs `await` to wait for
## the completion of the `Future`. ## the completion of the `Future`.
## ##
## .. code-block:: nim ## ```nim
## var game = await loadGame(name) ## var game = await loadGame(name)
## ```
## ##
## Often, you might work with callback-based API-s. You can wrap them with ## Often, you might work with callback-based API-s. You can wrap them with
## asynchronous procedures using promises and `newPromise`: ## asynchronous procedures using promises and `newPromise`:
## ##
## .. code-block:: nim ## ```nim
## proc loadGame(name: string): Future[Game] = ## proc loadGame(name: string): Future[Game] =
## var promise = newPromise() do (resolve: proc(response: Game)): ## var promise = newPromise() do (resolve: proc(response: Game)):
## cbBasedLoadGame(name) do (game: Game): ## cbBasedLoadGame(name) do (game: Game):
## resolve(game) ## resolve(game)
## return promise ## return promise
## ```
## ##
## Forward definitions work properly, you just need to always add the `{.async.}` pragma: ## Forward definitions work properly, you just need to always add the `{.async.}` pragma:
## ##
## .. code-block:: nim ## ```nim
## proc loadGame(name: string): Future[Game] {.async.} ## proc loadGame(name: string): Future[Game] {.async.}
## ```
## ##
## JavaScript compatibility ## JavaScript compatibility
## ======================== ## ========================
@ -57,7 +62,7 @@
## If you need to use this module with older versions of JavaScript, you can ## If you need to use this module with older versions of JavaScript, you can
## use a tool that backports the resulting JavaScript code, as babel. ## use a tool that backports the resulting JavaScript code, as babel.
# xxx code-block:: javascript above gives `LanguageXNotSupported` warning. # xxx code: javascript above gives `LanguageXNotSupported` warning.
when not defined(js) and not defined(nimsuggest): when not defined(js) and not defined(nimsuggest):
{.fatal: "Module asyncjs is designed to be used with the JavaScript backend.".} {.fatal: "Module asyncjs is designed to be used with the JavaScript backend.".}

View file

@ -1335,9 +1335,10 @@ since (1, 3):
## DOM Parser object (defined on browser only, may not be on NodeJS). ## DOM Parser object (defined on browser only, may not be on NodeJS).
## * https://developer.mozilla.org/en-US/docs/Web/API/DOMParser ## * https://developer.mozilla.org/en-US/docs/Web/API/DOMParser
## ##
## .. code-block:: nim ## ```nim
## let prsr = newDomParser() ## let prsr = newDomParser()
## discard prsr.parseFromString("<html><marquee>Hello World</marquee></html>".cstring, "text/html".cstring) ## discard prsr.parseFromString("<html><marquee>Hello World</marquee></html>".cstring, "text/html".cstring)
## ```
DomException* = ref DOMExceptionObj DomException* = ref DOMExceptionObj
## The DOMException interface represents an abnormal event (called an exception) ## The DOMException interface represents an abnormal event (called an exception)

View file

@ -268,15 +268,14 @@ macro `.()`*(obj: JsObject,
## so be careful when using this.) ## so be careful when using this.)
## ##
## Example: ## Example:
## ## ```nim
## .. code-block:: nim ## # Let's get back to the console example:
## ## var console {.importc, nodecl.}: JsObject
## # Let's get back to the console example: ## let res = console.log("I return undefined!")
## var console {.importc, nodecl.}: JsObject ## console.log(res) # This prints undefined, as console.log always returns
## let res = console.log("I return undefined!") ## # undefined. Thus one has to be careful, when using
## console.log(res) # This prints undefined, as console.log always returns ## # JsObject calls.
## # undefined. Thus one has to be careful, when using ## ```
## # JsObject calls.
var importString: string var importString: string
if validJsName($field): if validJsName($field):
importString = "#." & $field & "(@)" importString = "#." & $field & "(@)"
@ -407,21 +406,20 @@ macro `{}`*(typ: typedesc, xs: varargs[untyped]): auto =
## ##
## Example: ## Example:
## ##
## .. code-block:: nim ## ```nim
## # Let's say we have a type with a ton of fields, where some fields do not
## # need to be set, and we do not want those fields to be set to `nil`:
## type
## ExtremelyHugeType = ref object
## a, b, c, d, e, f, g: int
## h, i, j, k, l: cstring
## # And even more fields ...
## ##
## # Let's say we have a type with a ton of fields, where some fields do not ## let obj = ExtremelyHugeType{ a: 1, k: "foo".cstring, d: 42 }
## # need to be set, and we do not want those fields to be set to `nil`:
## type
## ExtremelyHugeType = ref object
## a, b, c, d, e, f, g: int
## h, i, j, k, l: cstring
## # And even more fields ...
##
## let obj = ExtremelyHugeType{ a: 1, k: "foo".cstring, d: 42 }
##
## # This generates roughly the same JavaScript as:
## {.emit: "var obj = {a: 1, k: "foo", d: 42};".}
## ##
## # This generates roughly the same JavaScript as:
## {.emit: "var obj = {a: 1, k: "foo", d: 42};".}
## ```
let a = ident"a" let a = ident"a"
var body = quote do: var body = quote do:
var `a` {.noinit.}: `typ` var `a` {.noinit.}: `typ`
@ -471,24 +469,25 @@ macro bindMethod*(procedure: typed): auto =
## Example: ## Example:
## ##
## We want to generate roughly this JavaScript: ## We want to generate roughly this JavaScript:
## ## ```js
## .. code-block:: js ## var obj = {a: 10};
## var obj = {a: 10}; ## obj.someMethod = function() {
## obj.someMethod = function() { ## return this.a + 42;
## return this.a + 42; ## };
## }; ## ```
## ##
## We can achieve this using the `bindMethod` macro: ## We can achieve this using the `bindMethod` macro:
## ##
## .. code-block:: nim ## ```nim
## let obj = JsObject{ a: 10 } ## let obj = JsObject{ a: 10 }
## proc someMethodImpl(that: JsObject): int = ## proc someMethodImpl(that: JsObject): int =
## that.a.to(int) + 42 ## that.a.to(int) + 42
## obj.someMethod = bindMethod someMethodImpl ## obj.someMethod = bindMethod someMethodImpl
## ##
## # Alternatively: ## # Alternatively:
## obj.someMethod = bindMethod ## obj.someMethod = bindMethod
## proc(that: JsObject): int = that.a.to(int) + 42 ## proc(that: JsObject): int = that.a.to(int) + 42
## ```
if not (procedure.kind == nnkSym or procedure.kind == nnkLambda): if not (procedure.kind == nnkSym or procedure.kind == nnkLambda):
error("Argument has to be a proc or a symbol corresponding to a proc.") error("Argument has to be a proc or a symbol corresponding to a proc.")
var var

View file

@ -13,7 +13,7 @@
## ##
## You can use this to build your own syntax highlighting, check this example: ## You can use this to build your own syntax highlighting, check this example:
## ##
## .. code:: Nim ## ```Nim
## let code = """for x in $int.high: echo x.ord mod 2 == 0""" ## let code = """for x in $int.high: echo x.ord mod 2 == 0"""
## var toknizr: GeneralTokenizer ## var toknizr: GeneralTokenizer
## initGeneralTokenizer(toknizr, code) ## initGeneralTokenizer(toknizr, code)
@ -31,19 +31,20 @@
## else: ## else:
## echo toknizr.kind # All the kinds of tokens can be processed here. ## echo toknizr.kind # All the kinds of tokens can be processed here.
## echo substr(code, toknizr.start, toknizr.length + toknizr.start - 1) ## echo substr(code, toknizr.start, toknizr.length + toknizr.start - 1)
## ```
## ##
## The proc `getSourceLanguage` can get the language `enum` from a string: ## The proc `getSourceLanguage` can get the language `enum` from a string:
## ## ```Nim
## .. code:: Nim
## for l in ["C", "c++", "jAvA", "Nim", "c#"]: echo getSourceLanguage(l) ## for l in ["C", "c++", "jAvA", "Nim", "c#"]: echo getSourceLanguage(l)
## ```
## ##
## There is also a `Cmd` pseudo-language supported, which is a simple generic ## There is also a `Cmd` pseudo-language supported, which is a simple generic
## shell/cmdline tokenizer (UNIX shell/Powershell/Windows Command): ## shell/cmdline tokenizer (UNIX shell/Powershell/Windows Command):
## no escaping, no programming language constructs besides variable definition ## no escaping, no programming language constructs besides variable definition
## at the beginning of line. It supports these operators: ## at the beginning of line. It supports these operators:
## ## ```Cmd
## .. code:: Cmd ## & && | || ( ) '' "" ; # for comments
## & && | || ( ) '' "" ; # for comments ## ```
## ##
## Instead of escaping always use quotes like here ## Instead of escaping always use quotes like here
## `nimgrep --ext:'nim|nims' file.name`:cmd: shows how to input ``|``. ## `nimgrep --ext:'nim|nims' file.name`:cmd: shows how to input ``|``.

View file

@ -153,12 +153,12 @@ proc initRstGenerator*(g: var RstGenerator, target: OutputTarget,
## ##
## Example: ## Example:
## ##
## .. code-block:: nim ## ```nim
##
## import packages/docutils/rstgen ## import packages/docutils/rstgen
## ##
## var gen: RstGenerator ## var gen: RstGenerator
## gen.initRstGenerator(outHtml, defaultConfig(), "filename", {}) ## gen.initRstGenerator(outHtml, defaultConfig(), "filename", {})
## ```
g.config = config g.config = config
g.target = target g.target = target
g.tocPart = @[] g.tocPart = @[]
@ -289,13 +289,12 @@ proc renderRstToOut*(d: var RstGenerator, n: PRstNode, result: var string) {.gcs
## Before using this proc you need to initialise a ``RstGenerator`` with ## Before using this proc you need to initialise a ``RstGenerator`` with
## ``initRstGenerator`` and parse a rst file with ``rstParse`` from the ## ``initRstGenerator`` and parse a rst file with ``rstParse`` from the
## `packages/docutils/rst module <rst.html>`_. Example: ## `packages/docutils/rst module <rst.html>`_. Example:
## ## ```nim
## .. code-block:: nim
##
## # ...configure gen and rst vars... ## # ...configure gen and rst vars...
## var generatedHtml = "" ## var generatedHtml = ""
## renderRstToOut(gen, rst, generatedHtml) ## renderRstToOut(gen, rst, generatedHtml)
## echo generatedHtml ## echo generatedHtml
## ```
proc renderAux(d: PDoc, n: PRstNode, result: var string) = proc renderAux(d: PDoc, n: PRstNode, result: var string) =
for i in countup(0, len(n)-1): renderRstToOut(d, n.sons[i], result) for i in countup(0, len(n)-1): renderRstToOut(d, n.sons[i], result)
@ -1602,12 +1601,13 @@ proc rstToHtml*(s: string, options: RstParseOptions,
## work. For an explanation of the ``config`` parameter see the ## work. For an explanation of the ``config`` parameter see the
## ``initRstGenerator`` proc. Example: ## ``initRstGenerator`` proc. Example:
## ##
## .. code-block:: nim ## ```nim
## import packages/docutils/rstgen, strtabs ## import packages/docutils/rstgen, strtabs
## ##
## echo rstToHtml("*Hello* **world**!", {}, ## echo rstToHtml("*Hello* **world**!", {},
## newStringTable(modeStyleInsensitive)) ## newStringTable(modeStyleInsensitive))
## # --> <em>Hello</em> <strong>world</strong>! ## # --> <em>Hello</em> <strong>world</strong>!
## ```
## ##
## If you need to allow the rst ``include`` directive or tweak the generated ## If you need to allow the rst ``include`` directive or tweak the generated
## output you have to create your own ``RstGenerator`` with ## output you have to create your own ``RstGenerator`` with

View file

@ -75,11 +75,11 @@ proc inotify_rm_watch*(fd: cint; wd: cint): cint {.cdecl,
iterator inotify_events*(evs: pointer, n: int): ptr InotifyEvent = iterator inotify_events*(evs: pointer, n: int): ptr InotifyEvent =
## Abstract the packed buffer interface to yield event object pointers. ## Abstract the packed buffer interface to yield event object pointers.
## ## ```Nim
## .. code-block:: Nim
## var evs = newSeq[byte](8192) # Already did inotify_init+add_watch ## var evs = newSeq[byte](8192) # Already did inotify_init+add_watch
## while (let n = read(fd, evs[0].addr, 8192); n) > 0: # read forever ## while (let n = read(fd, evs[0].addr, 8192); n) > 0: # read forever
## for e in inotify_events(evs[0].addr, n): echo e[].len # echo name lens ## for e in inotify_events(evs[0].addr, n): echo e[].len # echo name lens
## ```
var ev: ptr InotifyEvent = cast[ptr InotifyEvent](evs) var ev: ptr InotifyEvent = cast[ptr InotifyEvent](evs)
var n = n var n = n
while n > 0: while n > 0:

View file

@ -1093,11 +1093,11 @@ template onSignal*(signals: varargs[cint], body: untyped) =
## scope. ## scope.
## ##
## Example: ## Example:
## ## ```Nim
## .. code-block::
## from std/posix import SIGINT, SIGTERM, onSignal ## from std/posix import SIGINT, SIGTERM, onSignal
## onSignal(SIGINT, SIGTERM): ## onSignal(SIGINT, SIGTERM):
## echo "bye from signal ", sig ## echo "bye from signal ", sig
## ```
for s in signals: for s in signals:
handle_signal(s, handle_signal(s,

View file

@ -379,22 +379,22 @@ func sort*[T](a: var openArray[T],
## `cmp`, you may use `system.cmp` or instead call the overloaded ## `cmp`, you may use `system.cmp` or instead call the overloaded
## version of `sort`, which uses `system.cmp`. ## version of `sort`, which uses `system.cmp`.
## ##
## .. code-block:: nim ## ```nim
## ## sort(myIntArray, system.cmp[int])
## sort(myIntArray, system.cmp[int]) ## # do not use cmp[string] here as we want to use the specialized
## # do not use cmp[string] here as we want to use the specialized ## # overload:
## # overload: ## sort(myStrArray, system.cmp)
## sort(myStrArray, system.cmp) ## ```
## ##
## You can inline adhoc comparison procs with the `do notation ## You can inline adhoc comparison procs with the `do notation
## <manual_experimental.html#do-notation>`_. Example: ## <manual_experimental.html#do-notation>`_. Example:
## ##
## .. code-block:: nim ## ```nim
##
## people.sort do (x, y: Person) -> int: ## people.sort do (x, y: Person) -> int:
## result = cmp(x.surname, y.surname) ## result = cmp(x.surname, y.surname)
## if result == 0: ## if result == 0:
## result = cmp(x.name, y.name) ## result = cmp(x.name, y.name)
## ```
## ##
## **See also:** ## **See also:**
## * `sort proc<#sort,openArray[T]>`_ ## * `sort proc<#sort,openArray[T]>`_

View file

@ -41,13 +41,13 @@
## requested amount of data is read **or** an exception occurs. ## requested amount of data is read **or** an exception occurs.
## ##
## Code to read some data from a socket may look something like this: ## Code to read some data from a socket may look something like this:
## ## ```Nim
## .. code-block:: Nim ## var future = socket.recv(100)
## var future = socket.recv(100) ## future.addCallback(
## future.addCallback( ## proc () =
## proc () = ## echo(future.read)
## echo(future.read) ## )
## ) ## ```
## ##
## All asynchronous functions returning a `Future` will not block. They ## All asynchronous functions returning a `Future` will not block. They
## will not however return immediately. An asynchronous function will have ## will not however return immediately. An asynchronous function will have
@ -108,24 +108,24 @@
## You can handle exceptions in the same way as in ordinary Nim code; ## You can handle exceptions in the same way as in ordinary Nim code;
## by using the try statement: ## by using the try statement:
## ##
## ## ```Nim
## .. code-block:: Nim
## try: ## try:
## let data = await sock.recv(100) ## let data = await sock.recv(100)
## echo("Received ", data) ## echo("Received ", data)
## except: ## except:
## # Handle exception ## # Handle exception
## ## ```
##
## ##
## An alternative approach to handling exceptions is to use `yield` on a future ## An alternative approach to handling exceptions is to use `yield` on a future
## then check the future's `failed` property. For example: ## then check the future's `failed` property. For example:
## ##
## .. code-block:: Nim ## ```Nim
## var future = sock.recv(100) ## var future = sock.recv(100)
## yield future ## yield future
## if future.failed: ## if future.failed:
## # Handle exception ## # Handle exception
## ```
##
## ##
## Discarding futures ## Discarding futures
## ================== ## ==================

View file

@ -9,18 +9,19 @@
## This module implements asynchronous file reading and writing. ## This module implements asynchronous file reading and writing.
## ##
## .. code-block:: Nim ## ```Nim
## import std/[asyncfile, asyncdispatch, os] ## import std/[asyncfile, asyncdispatch, os]
## ##
## proc main() {.async.} = ## proc main() {.async.} =
## var file = openAsync(getTempDir() / "foobar.txt", fmReadWrite) ## var file = openAsync(getTempDir() / "foobar.txt", fmReadWrite)
## await file.write("test") ## await file.write("test")
## file.setFilePos(0) ## file.setFilePos(0)
## let data = await file.readAll() ## let data = await file.readAll()
## doAssert data == "test" ## doAssert data == "test"
## file.close() ## file.close()
## ##
## waitFor main() ## waitFor main()
## ```
import asyncdispatch, os import asyncdispatch, os

View file

@ -21,13 +21,14 @@
## In order to begin any sort of transfer of files you must first ## In order to begin any sort of transfer of files you must first
## connect to an FTP server. You can do so with the `connect` procedure. ## connect to an FTP server. You can do so with the `connect` procedure.
## ##
## .. code-block:: Nim ## ```Nim
## import std/[asyncdispatch, asyncftpclient] ## import std/[asyncdispatch, asyncftpclient]
## proc main() {.async.} = ## proc main() {.async.} =
## var ftp = newAsyncFtpClient("example.com", user = "test", pass = "test") ## var ftp = newAsyncFtpClient("example.com", user = "test", pass = "test")
## await ftp.connect() ## await ftp.connect()
## echo("Connected") ## echo("Connected")
## waitFor(main()) ## waitFor(main())
## ```
## ##
## A new `main` async procedure must be declared to allow the use of the ## A new `main` async procedure must be declared to allow the use of the
## `await` keyword. The connection will complete asynchronously and the ## `await` keyword. The connection will complete asynchronously and the
@ -41,16 +42,17 @@
## working directory before you do so with the `pwd` procedure, you can also ## working directory before you do so with the `pwd` procedure, you can also
## instead specify an absolute path. ## instead specify an absolute path.
## ##
## .. code-block:: Nim ## ```Nim
## import std/[asyncdispatch, asyncftpclient] ## import std/[asyncdispatch, asyncftpclient]
## proc main() {.async.} = ## proc main() {.async.} =
## var ftp = newAsyncFtpClient("example.com", user = "test", pass = "test") ## var ftp = newAsyncFtpClient("example.com", user = "test", pass = "test")
## await ftp.connect() ## await ftp.connect()
## let currentDir = await ftp.pwd() ## let currentDir = await ftp.pwd()
## assert currentDir == "/home/user/" ## assert currentDir == "/home/user/"
## await ftp.store("file.txt", "file.txt") ## await ftp.store("file.txt", "file.txt")
## echo("File finished uploading") ## echo("File finished uploading")
## waitFor(main()) ## waitFor(main())
## ```
## ##
## Checking the progress of a file transfer ## Checking the progress of a file transfer
## ======================================== ## ========================================
@ -62,20 +64,21 @@
## Procs that take an `onProgressChanged` callback will call this every ## Procs that take an `onProgressChanged` callback will call this every
## `progressInterval` milliseconds. ## `progressInterval` milliseconds.
## ##
## .. code-block:: Nim ## ```Nim
## import std/[asyncdispatch, asyncftpclient] ## import std/[asyncdispatch, asyncftpclient]
## ##
## proc onProgressChanged(total, progress: BiggestInt, ## proc onProgressChanged(total, progress: BiggestInt,
## speed: float) {.async.} = ## speed: float) {.async.} =
## echo("Uploaded ", progress, " of ", total, " bytes") ## echo("Uploaded ", progress, " of ", total, " bytes")
## echo("Current speed: ", speed, " kb/s") ## echo("Current speed: ", speed, " kb/s")
## ##
## proc main() {.async.} = ## proc main() {.async.} =
## var ftp = newAsyncFtpClient("example.com", user = "test", pass = "test", progressInterval = 500) ## var ftp = newAsyncFtpClient("example.com", user = "test", pass = "test", progressInterval = 500)
## await ftp.connect() ## await ftp.connect()
## await ftp.store("file.txt", "/home/user/file.txt", onProgressChanged) ## await ftp.store("file.txt", "/home/user/file.txt", onProgressChanged)
## echo("File finished uploading") ## echo("File finished uploading")
## waitFor(main()) ## waitFor(main())
## ```
import asyncdispatch, asyncnet, nativesockets, strutils, parseutils, os, times import asyncdispatch, asyncnet, nativesockets, strutils, parseutils, os, times

View file

@ -65,8 +65,7 @@
## ##
## The following example demonstrates a simple chat server. ## The following example demonstrates a simple chat server.
## ##
## .. code-block:: Nim ## ```Nim
##
## import std/[asyncnet, asyncdispatch] ## import std/[asyncnet, asyncdispatch]
## ##
## var clients {.threadvar.}: seq[AsyncSocket] ## var clients {.threadvar.}: seq[AsyncSocket]
@ -93,7 +92,7 @@
## ##
## asyncCheck serve() ## asyncCheck serve()
## runForever() ## runForever()
## ## ```
import std/private/since import std/private/since

View file

@ -69,8 +69,9 @@ proc openDefaultBrowser*(url: string) =
## ##
## This proc doesn't raise an exception on error, beware. ## This proc doesn't raise an exception on error, beware.
## ##
## .. code-block:: nim ## ```nim
## block: openDefaultBrowser("https://nim-lang.org") ## block: openDefaultBrowser("https://nim-lang.org")
## ```
doAssert url.len > 0, "URL must not be empty string" doAssert url.len > 0, "URL must not be empty string"
openDefaultBrowserImpl(url) openDefaultBrowserImpl(url)
@ -85,10 +86,11 @@ proc openDefaultBrowser*() {.since: (1, 1).} =
## ##
## This proc doesn't raise an exception on error, beware. ## This proc doesn't raise an exception on error, beware.
## ##
## ```nim
## block: openDefaultBrowser()
## ```
##
## **See also:** ## **See also:**
## ##
## * https://tools.ietf.org/html/rfc6694#section-3 ## * https://tools.ietf.org/html/rfc6694#section-3
##
## .. code-block:: nim
## block: openDefaultBrowser()
openDefaultBrowserImpl("http:about:blank") # See IETF RFC-6694 Section 3. openDefaultBrowserImpl("http:about:blank") # See IETF RFC-6694 Section 3.

View file

@ -9,25 +9,25 @@
## This module implements helper procs for CGI applications. Example: ## This module implements helper procs for CGI applications. Example:
## ##
## .. code-block:: Nim ## ```Nim
## import std/[strtabs, cgi]
## ##
## import std/[strtabs, cgi] ## # Fill the values when debugging:
## ## when debug:
## # Fill the values when debugging: ## setTestData("name", "Klaus", "password", "123456")
## when debug: ## # read the data into `myData`
## setTestData("name", "Klaus", "password", "123456") ## var myData = readData()
## # read the data into `myData` ## # check that the data's variable names are "name" or "password"
## var myData = readData() ## validateData(myData, "name", "password")
## # check that the data's variable names are "name" or "password" ## # start generating content:
## validateData(myData, "name", "password") ## writeContentType()
## # start generating content: ## # generate content:
## writeContentType() ## write(stdout, "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n")
## # generate content: ## write(stdout, "<html><head><title>Test</title></head><body>\n")
## write(stdout, "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n") ## writeLine(stdout, "your name: " & myData["name"])
## write(stdout, "<html><head><title>Test</title></head><body>\n") ## writeLine(stdout, "your password: " & myData["password"])
## writeLine(stdout, "your name: " & myData["name"]) ## writeLine(stdout, "</body></html>")
## writeLine(stdout, "your password: " & myData["password"]) ## ```
## writeLine(stdout, "</body></html>")
import strutils, os, strtabs, cookies, uri import strutils, os, strtabs, cookies, uri
export uri.encodeUrl, uri.decodeUrl export uri.encodeUrl, uri.decodeUrl
@ -252,9 +252,9 @@ proc setTestData*(keysvalues: varargs[string]) =
## Fills the appropriate environment variables to test your CGI application. ## Fills the appropriate environment variables to test your CGI application.
## This can only simulate the 'GET' request method. `keysvalues` should ## This can only simulate the 'GET' request method. `keysvalues` should
## provide embedded (name, value)-pairs. Example: ## provide embedded (name, value)-pairs. Example:
## ## ```Nim
## .. code-block:: Nim ## setTestData("name", "Hanz", "password", "12345")
## setTestData("name", "Hanz", "password", "12345") ## ```
putEnv("REQUEST_METHOD", "GET") putEnv("REQUEST_METHOD", "GET")
var i = 0 var i = 0
var query = "" var query = ""
@ -269,9 +269,9 @@ proc setTestData*(keysvalues: varargs[string]) =
proc writeContentType*() = proc writeContentType*() =
## Calls this before starting to send your HTML data to `stdout`. This ## Calls this before starting to send your HTML data to `stdout`. This
## implements this part of the CGI protocol: ## implements this part of the CGI protocol:
## ## ```Nim
## .. code-block:: Nim ## write(stdout, "Content-type: text/html\n\n")
## write(stdout, "Content-type: text/html\n\n") ## ```
write(stdout, "Content-type: text/html\n\n") write(stdout, "Content-type: text/html\n\n")
proc resetForStacktrace() = proc resetForStacktrace() =