mirror of
https://github.com/nim-lang/Nim.git
synced 2026-04-18 21:40:32 +00:00
Markdown code blocks migration part 7 (#20547)
This commit is contained in:
@@ -26,8 +26,9 @@
|
||||
## That is, using the `?` (question mark) to signify the place where a
|
||||
## value should be placed. For example:
|
||||
##
|
||||
## .. code-block:: Nim
|
||||
## sql"INSERT INTO myTable (colA, colB, colC) VALUES (?, ?, ?)"
|
||||
## ```Nim
|
||||
## sql"INSERT INTO myTable (colA, colB, colC) VALUES (?, ?, ?)"
|
||||
## ```
|
||||
##
|
||||
##
|
||||
## Examples
|
||||
@@ -36,57 +37,60 @@
|
||||
## Opening a connection to a database
|
||||
## ----------------------------------
|
||||
##
|
||||
## .. code-block:: Nim
|
||||
## import std/db_odbc
|
||||
## var db = open("localhost", "user", "password", "dbname")
|
||||
## db.close()
|
||||
## ```Nim
|
||||
## import std/db_odbc
|
||||
## var db = open("localhost", "user", "password", "dbname")
|
||||
## db.close()
|
||||
## ```
|
||||
##
|
||||
## Creating a table
|
||||
## ----------------
|
||||
##
|
||||
## .. code-block:: Nim
|
||||
## db.exec(sql"DROP TABLE IF EXISTS myTable")
|
||||
## db.exec(sql("""CREATE TABLE myTable (
|
||||
## id integer,
|
||||
## name varchar(50) not null)"""))
|
||||
## ```Nim
|
||||
## db.exec(sql"DROP TABLE IF EXISTS myTable")
|
||||
## db.exec(sql("""CREATE TABLE myTable (
|
||||
## id integer,
|
||||
## name varchar(50) not null)"""))
|
||||
## ```
|
||||
##
|
||||
## Inserting data
|
||||
## --------------
|
||||
##
|
||||
## .. code-block:: Nim
|
||||
## db.exec(sql"INSERT INTO myTable (id, name) VALUES (0, ?)",
|
||||
## "Andreas")
|
||||
## ```Nim
|
||||
## db.exec(sql"INSERT INTO myTable (id, name) VALUES (0, ?)",
|
||||
## "Andreas")
|
||||
## ```
|
||||
##
|
||||
## 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("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"START TRANSACTION")
|
||||
## for i in 1..1000:
|
||||
## theDb.exec(sql"INSERT INTO myTestTbl (name,i,f) VALUES (?,?,?)",
|
||||
## "Item#" & $i, i, sqrt(i.float))
|
||||
## theDb.exec(sql"COMMIT")
|
||||
##
|
||||
## theDb.exec(sql"START TRANSACTION")
|
||||
## for i in 1..1000:
|
||||
## 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"):
|
||||
## echo x
|
||||
##
|
||||
## for x in theDb.fastRows(sql"select * from myTestTbl"):
|
||||
## echo x
|
||||
## let id = theDb.tryInsertId(sql"INSERT INTO myTestTbl (name,i,f) VALUES (?,?,?)",
|
||||
## "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 (?,?,?)",
|
||||
## "Item#1001", 1001, sqrt(1001.0))
|
||||
## echo "Inserted item: ", theDb.getValue(sql"SELECT name FROM myTestTbl WHERE id=?", id)
|
||||
##
|
||||
## theDb.close()
|
||||
## theDb.close()
|
||||
## ```
|
||||
|
||||
import strutils, odbcsql
|
||||
import db_common
|
||||
|
||||
@@ -20,8 +20,9 @@
|
||||
## That is, using the `?` (question mark) to signify the place where a
|
||||
## value should be placed. For example:
|
||||
##
|
||||
## .. code-block:: Nim
|
||||
## sql"INSERT INTO myTable (colA, colB, colC) VALUES (?, ?, ?)"
|
||||
## ```Nim
|
||||
## sql"INSERT INTO myTable (colA, colB, colC) VALUES (?, ?, ?)"
|
||||
## ```
|
||||
##
|
||||
## **Note**: There are two approaches to parameter substitution support by
|
||||
## this module.
|
||||
@@ -30,12 +31,13 @@
|
||||
##
|
||||
## 2. `SqlPrepared` using `$1, $2, $3, ...`
|
||||
##
|
||||
## .. code-block:: Nim
|
||||
## ```Nim
|
||||
## prepare(db, "myExampleInsert",
|
||||
## sql"""INSERT INTO myTable
|
||||
## (colA, colB, colC)
|
||||
## VALUES ($1, $2, $3)""",
|
||||
## 3)
|
||||
## ```
|
||||
##
|
||||
##
|
||||
## Unix Socket
|
||||
@@ -46,11 +48,12 @@
|
||||
##
|
||||
## 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
|
||||
## let db = db_postgres.open("/run/postgresql", "user", "password", "database")
|
||||
## echo db.getAllRows(sql"SELECT version();")
|
||||
## db.close()
|
||||
## ```
|
||||
##
|
||||
## The socket file path is operating system specific and distribution specific,
|
||||
## additional configuration may or may not be needed on your `postgresql.conf`.
|
||||
@@ -63,26 +66,29 @@
|
||||
## Opening a connection to a database
|
||||
## ----------------------------------
|
||||
##
|
||||
## .. code-block:: Nim
|
||||
## import std/db_postgres
|
||||
## let db = open("localhost", "user", "password", "dbname")
|
||||
## db.close()
|
||||
## ```Nim
|
||||
## import std/db_postgres
|
||||
## let db = open("localhost", "user", "password", "dbname")
|
||||
## db.close()
|
||||
## ```
|
||||
##
|
||||
## Creating a table
|
||||
## ----------------
|
||||
##
|
||||
## .. code-block:: Nim
|
||||
## db.exec(sql"DROP TABLE IF EXISTS myTable")
|
||||
## db.exec(sql("""CREATE TABLE myTable (
|
||||
## id integer,
|
||||
## name varchar(50) not null)"""))
|
||||
## ```Nim
|
||||
## db.exec(sql"DROP TABLE IF EXISTS myTable")
|
||||
## db.exec(sql("""CREATE TABLE myTable (
|
||||
## id integer,
|
||||
## name varchar(50) not null)"""))
|
||||
## ```
|
||||
##
|
||||
## Inserting data
|
||||
## --------------
|
||||
##
|
||||
## .. code-block:: Nim
|
||||
## db.exec(sql"INSERT INTO myTable (id, name) VALUES (0, ?)",
|
||||
## "Dominik")
|
||||
## ```Nim
|
||||
## db.exec(sql"INSERT INTO myTable (id, name) VALUES (0, ?)",
|
||||
## "Dominik")
|
||||
## ```
|
||||
import strutils, postgres
|
||||
|
||||
import db_common
|
||||
@@ -609,10 +615,9 @@ proc open*(connection, user, password, database: string): DbConn {.
|
||||
## connect.
|
||||
##
|
||||
## Example:
|
||||
##
|
||||
## .. code-block:: nim
|
||||
##
|
||||
## con = open("", "", "", "host=localhost port=5432 dbname=mydb")
|
||||
## ```nim
|
||||
## con = open("", "", "", "host=localhost port=5432 dbname=mydb")
|
||||
## ```
|
||||
##
|
||||
## See http://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING
|
||||
## for more information.
|
||||
|
||||
@@ -26,79 +26,78 @@
|
||||
## That is, using the `?` (question mark) to signify the place where a
|
||||
## value should be placed. For example:
|
||||
##
|
||||
## .. code-block:: Nim
|
||||
##
|
||||
## sql"INSERT INTO my_table (colA, colB, colC) VALUES (?, ?, ?)"
|
||||
## ```Nim
|
||||
## sql"INSERT INTO my_table (colA, colB, colC) VALUES (?, ?, ?)"
|
||||
## ```
|
||||
##
|
||||
## 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.
|
||||
## let db = open("mytest.db", "", "", "")
|
||||
## db.close()
|
||||
## # user, password, database name can be empty.
|
||||
## # These params are not used on db_sqlite module.
|
||||
## let db = open("mytest.db", "", "", "")
|
||||
## db.close()
|
||||
## ```
|
||||
##
|
||||
## Creating a table
|
||||
## ----------------
|
||||
##
|
||||
## .. code-block:: Nim
|
||||
##
|
||||
## db.exec(sql"DROP TABLE IF EXISTS my_table")
|
||||
## db.exec(sql"""CREATE TABLE my_table (
|
||||
## id INTEGER,
|
||||
## name VARCHAR(50) NOT NULL
|
||||
## )""")
|
||||
## ```Nim
|
||||
## db.exec(sql"DROP TABLE IF EXISTS my_table")
|
||||
## db.exec(sql"""CREATE TABLE my_table (
|
||||
## id INTEGER,
|
||||
## name VARCHAR(50) NOT NULL
|
||||
## )""")
|
||||
## ```
|
||||
##
|
||||
## Inserting data
|
||||
## --------------
|
||||
##
|
||||
## .. code-block:: Nim
|
||||
##
|
||||
## db.exec(sql"INSERT INTO my_table (id, name) VALUES (0, ?)",
|
||||
## "Jack")
|
||||
## ```Nim
|
||||
## db.exec(sql"INSERT INTO my_table (id, name) VALUES (0, ?)",
|
||||
## "Jack")
|
||||
## ```
|
||||
##
|
||||
## 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"""CREATE TABLE my_table (
|
||||
## id INTEGER PRIMARY KEY,
|
||||
## name VARCHAR(50) NOT NULL,
|
||||
## i INT(11),
|
||||
## f DECIMAL(18, 10)
|
||||
## )""")
|
||||
## db.exec(sql"BEGIN")
|
||||
## for i in 1..1000:
|
||||
## db.exec(sql"INSERT INTO my_table (name, i, f) VALUES (?, ?, ?)",
|
||||
## "Item#" & $i, i, sqrt(i.float))
|
||||
## db.exec(sql"COMMIT")
|
||||
##
|
||||
## db.exec(sql"BEGIN")
|
||||
## for i in 1..1000:
|
||||
## 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"):
|
||||
## echo x
|
||||
##
|
||||
## for x in db.fastRows(sql"SELECT * FROM my_table"):
|
||||
## echo x
|
||||
## let id = db.tryInsertId(sql"""INSERT INTO my_table (name, i, f)
|
||||
## 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)
|
||||
## VALUES (?, ?, ?)""",
|
||||
## "Item#1001", 1001, sqrt(1001.0))
|
||||
## echo "Inserted item: ", db.getValue(sql"SELECT name FROM my_table WHERE id=?", id)
|
||||
##
|
||||
## db.close()
|
||||
## db.close()
|
||||
## ```
|
||||
##
|
||||
## Storing binary data example
|
||||
##----------------------------
|
||||
##
|
||||
## .. code-block:: nim
|
||||
##
|
||||
## ```nim
|
||||
## import std/random
|
||||
##
|
||||
## ## Generate random float datas
|
||||
@@ -144,6 +143,7 @@
|
||||
## doAssert res == orig
|
||||
##
|
||||
## db.close()
|
||||
## ```
|
||||
##
|
||||
##
|
||||
## Note
|
||||
@@ -187,13 +187,12 @@ proc dbError*(db: DbConn) {.noreturn.} =
|
||||
## Raises a `DbError` exception.
|
||||
##
|
||||
## **Examples:**
|
||||
##
|
||||
## .. code-block:: Nim
|
||||
##
|
||||
## let db = open("mytest.db", "", "", "")
|
||||
## if not db.tryExec(sql"SELECT * FROM not_exist_table"):
|
||||
## dbError(db)
|
||||
## db.close()
|
||||
## ```Nim
|
||||
## let db = open("mytest.db", "", "", "")
|
||||
## if not db.tryExec(sql"SELECT * FROM not_exist_table"):
|
||||
## dbError(db)
|
||||
## db.close()
|
||||
## ```
|
||||
var e: ref DbError
|
||||
new(e)
|
||||
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.
|
||||
##
|
||||
## **Examples:**
|
||||
##
|
||||
## .. code-block:: Nim
|
||||
##
|
||||
## let db = open("mytest.db", "", "", "")
|
||||
## if not db.tryExec(sql"SELECT * FROM my_table"):
|
||||
## dbError(db)
|
||||
## db.close()
|
||||
## ```Nim
|
||||
## let db = open("mytest.db", "", "", "")
|
||||
## if not db.tryExec(sql"SELECT * FROM my_table"):
|
||||
## dbError(db)
|
||||
## db.close()
|
||||
## ```
|
||||
assert(not db.isNil, "Database not connected.")
|
||||
var q = dbFormat(query, args)
|
||||
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.
|
||||
##
|
||||
## **Examples:**
|
||||
##
|
||||
## .. code-block:: Nim
|
||||
##
|
||||
## let db = open("mytest.db", "", "", "")
|
||||
## try:
|
||||
## db.exec(sql"INSERT INTO my_table (id, name) VALUES (?, ?)",
|
||||
## 1, "item#1")
|
||||
## except:
|
||||
## stderr.writeLine(getCurrentExceptionMsg())
|
||||
## finally:
|
||||
## db.close()
|
||||
## ```Nim
|
||||
## let db = open("mytest.db", "", "", "")
|
||||
## try:
|
||||
## db.exec(sql"INSERT INTO my_table (id, name) VALUES (?, ?)",
|
||||
## 1, "item#1")
|
||||
## except:
|
||||
## stderr.writeLine(getCurrentExceptionMsg())
|
||||
## finally:
|
||||
## db.close()
|
||||
## ```
|
||||
if not tryExec(db, query, args): dbError(db)
|
||||
|
||||
proc newRow(L: int): Row =
|
||||
@@ -310,24 +307,24 @@ iterator fastRows*(db: DbConn, query: SqlQuery,
|
||||
##
|
||||
## **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:
|
||||
## # | id | name |
|
||||
## # |----|----------|
|
||||
## # | 1 | item#1 |
|
||||
## # | 2 | item#2 |
|
||||
## for row in db.fastRows(sql"SELECT id, name FROM my_table"):
|
||||
## echo row
|
||||
##
|
||||
## for row in db.fastRows(sql"SELECT id, name FROM my_table"):
|
||||
## echo row
|
||||
## # Output:
|
||||
## # @["1", "item#1"]
|
||||
## # @["2", "item#2"]
|
||||
##
|
||||
## # Output:
|
||||
## # @["1", "item#1"]
|
||||
## # @["2", "item#2"]
|
||||
##
|
||||
## db.close()
|
||||
## db.close()
|
||||
## ```
|
||||
var stmt = setupQuery(db, query, args)
|
||||
var L = (column_count(stmt))
|
||||
var result = newRow(L)
|
||||
@@ -359,8 +356,7 @@ iterator instantRows*(db: DbConn, query: SqlQuery,
|
||||
##
|
||||
## **Examples:**
|
||||
##
|
||||
## .. code-block:: Nim
|
||||
##
|
||||
## ```Nim
|
||||
## let db = open("mytest.db", "", "", "")
|
||||
##
|
||||
## # Records of my_table:
|
||||
@@ -383,6 +379,7 @@ iterator instantRows*(db: DbConn, query: SqlQuery,
|
||||
## # length:2
|
||||
##
|
||||
## db.close()
|
||||
## ```
|
||||
var stmt = setupQuery(db, query, args)
|
||||
try:
|
||||
while step(stmt) == SQLITE_ROW:
|
||||
@@ -429,28 +426,28 @@ iterator instantRows*(db: DbConn; columns: var DbColumns; query: SqlQuery,
|
||||
##
|
||||
## **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:
|
||||
## # | id | name |
|
||||
## # |----|----------|
|
||||
## # | 1 | item#1 |
|
||||
## # | 2 | item#2 |
|
||||
## var columns: DbColumns
|
||||
## for row in db.instantRows(columns, sql"SELECT * FROM my_table"):
|
||||
## discard
|
||||
## echo columns[0]
|
||||
##
|
||||
## var columns: DbColumns
|
||||
## for row in db.instantRows(columns, sql"SELECT * FROM my_table"):
|
||||
## discard
|
||||
## echo columns[0]
|
||||
## # Output:
|
||||
## # (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)
|
||||
##
|
||||
## # Output:
|
||||
## # (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()
|
||||
## db.close()
|
||||
## ```
|
||||
var stmt = setupQuery(db, query, args)
|
||||
setColumns(columns, stmt)
|
||||
try:
|
||||
@@ -490,28 +487,28 @@ proc getRow*(db: DbConn, query: SqlQuery,
|
||||
##
|
||||
## **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:
|
||||
## # | id | name |
|
||||
## # |----|----------|
|
||||
## # | 1 | item#1 |
|
||||
## # | 2 | item#2 |
|
||||
## doAssert db.getRow(sql"SELECT id, name FROM my_table"
|
||||
## ) == Row(@["1", "item#1"])
|
||||
## doAssert db.getRow(sql"SELECT id, name FROM my_table WHERE id = ?",
|
||||
## 2) == Row(@["2", "item#2"])
|
||||
##
|
||||
## doAssert db.getRow(sql"SELECT id, name FROM my_table"
|
||||
## ) == Row(@["1", "item#1"])
|
||||
## doAssert db.getRow(sql"SELECT id, name FROM my_table WHERE id = ?",
|
||||
## 2) == Row(@["2", "item#2"])
|
||||
##
|
||||
## # Returns empty.
|
||||
## doAssert db.getRow(sql"INSERT INTO my_table (id, name) VALUES (?, ?)",
|
||||
## 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()
|
||||
## # Returns empty.
|
||||
## doAssert db.getRow(sql"INSERT INTO my_table (id, name) VALUES (?, ?)",
|
||||
## 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 L = (column_count(stmt))
|
||||
result = newRow(L)
|
||||
@@ -525,18 +522,18 @@ proc getAllRows*(db: DbConn, query: SqlQuery,
|
||||
##
|
||||
## **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:
|
||||
## # | id | name |
|
||||
## # |----|----------|
|
||||
## # | 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()
|
||||
## doAssert db.getAllRows(sql"SELECT id, name FROM my_table") == @[Row(@["1", "item#1"]), Row(@["2", "item#2"])]
|
||||
## db.close()
|
||||
## ```
|
||||
result = @[]
|
||||
for r in fastRows(db, query, args):
|
||||
result.add(r)
|
||||
@@ -554,24 +551,24 @@ iterator rows*(db: DbConn, query: SqlQuery,
|
||||
##
|
||||
## **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:
|
||||
## # | id | name |
|
||||
## # |----|----------|
|
||||
## # | 1 | item#1 |
|
||||
## # | 2 | item#2 |
|
||||
## for row in db.rows(sql"SELECT id, name FROM my_table"):
|
||||
## echo row
|
||||
##
|
||||
## for row in db.rows(sql"SELECT id, name FROM my_table"):
|
||||
## echo row
|
||||
## ## Output:
|
||||
## ## @["1", "item#1"]
|
||||
## ## @["2", "item#2"]
|
||||
##
|
||||
## ## Output:
|
||||
## ## @["1", "item#1"]
|
||||
## ## @["2", "item#2"]
|
||||
##
|
||||
## db.close()
|
||||
## db.close()
|
||||
## ```
|
||||
for r in fastRows(db, query, args): yield r
|
||||
|
||||
iterator rows*(db: DbConn, stmtName: SqlPrepared): Row
|
||||
@@ -586,22 +583,22 @@ proc getValue*(db: DbConn, query: SqlQuery,
|
||||
##
|
||||
## **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:
|
||||
## # | id | name |
|
||||
## # |----|----------|
|
||||
## # | 1 | item#1 |
|
||||
## # | 2 | item#2 |
|
||||
## doAssert db.getValue(sql"SELECT name FROM my_table WHERE id = ?",
|
||||
## 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"
|
||||
##
|
||||
## doAssert db.getValue(sql"SELECT name FROM my_table WHERE id = ?",
|
||||
## 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()
|
||||
## db.close()
|
||||
## ```
|
||||
var stmt = setupQuery(db, query, args)
|
||||
if step(stmt) == SQLITE_ROW:
|
||||
let cb = column_bytes(stmt, 0)
|
||||
@@ -643,14 +640,14 @@ proc tryInsertID*(db: DbConn, query: SqlQuery,
|
||||
##
|
||||
## **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", "", "", "")
|
||||
## db.exec(sql"CREATE TABLE my_table (id INTEGER, name VARCHAR(50) NOT NULL)")
|
||||
##
|
||||
## doAssert db.tryInsertID(sql"INSERT INTO not_exist_table (id, name) VALUES (?, ?)",
|
||||
## 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.")
|
||||
var q = dbFormat(query, args)
|
||||
var stmt: sqlite3.PStmt
|
||||
@@ -674,21 +671,21 @@ proc insertID*(db: DbConn, query: SqlQuery,
|
||||
##
|
||||
## **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", "", "", "")
|
||||
## db.exec(sql"CREATE TABLE my_table (id INTEGER, name VARCHAR(50) NOT NULL)")
|
||||
## for i in 0..2:
|
||||
## 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:
|
||||
## let id = db.insertID(sql"INSERT INTO my_table (id, name) VALUES (?, ?)", i, "item#" & $i)
|
||||
## echo "LoopIndex = ", i, ", InsertID = ", id
|
||||
## # Output:
|
||||
## # LoopIndex = 0, InsertID = 1
|
||||
## # LoopIndex = 1, InsertID = 2
|
||||
## # LoopIndex = 2, InsertID = 3
|
||||
##
|
||||
## # Output:
|
||||
## # LoopIndex = 0, InsertID = 1
|
||||
## # LoopIndex = 1, InsertID = 2
|
||||
## # LoopIndex = 2, InsertID = 3
|
||||
##
|
||||
## db.close()
|
||||
## db.close()
|
||||
## ```
|
||||
result = tryInsertID(db, query, args)
|
||||
if result < 0: dbError(db)
|
||||
|
||||
@@ -713,19 +710,19 @@ proc execAffectedRows*(db: DbConn, query: SqlQuery,
|
||||
##
|
||||
## **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:
|
||||
## # | id | name |
|
||||
## # |----|----------|
|
||||
## # | 1 | item#1 |
|
||||
## # | 2 | item#2 |
|
||||
## doAssert db.execAffectedRows(sql"UPDATE my_table SET name = 'TEST'") == 2
|
||||
##
|
||||
## doAssert db.execAffectedRows(sql"UPDATE my_table SET name = 'TEST'") == 2
|
||||
##
|
||||
## db.close()
|
||||
## db.close()
|
||||
## ```
|
||||
exec(db, query, args)
|
||||
result = changes(db)
|
||||
|
||||
@@ -738,11 +735,10 @@ proc close*(db: DbConn) {.tags: [DbEffect].} =
|
||||
## Closes the database connection.
|
||||
##
|
||||
## **Examples:**
|
||||
##
|
||||
## .. code-block:: Nim
|
||||
##
|
||||
## let db = open("mytest.db", "", "", "")
|
||||
## db.close()
|
||||
## ```Nim
|
||||
## let db = open("mytest.db", "", "", "")
|
||||
## db.close()
|
||||
## ```
|
||||
if sqlite3.close(db) != SQLITE_OK: dbError(db)
|
||||
|
||||
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`.
|
||||
##
|
||||
## **Examples:**
|
||||
##
|
||||
## .. code-block:: Nim
|
||||
##
|
||||
## try:
|
||||
## let db = open("mytest.db", "", "", "")
|
||||
## ## do something...
|
||||
## ## db.getAllRows(sql"SELECT * FROM my_table")
|
||||
## db.close()
|
||||
## except:
|
||||
## stderr.writeLine(getCurrentExceptionMsg())
|
||||
## ```Nim
|
||||
## try:
|
||||
## let db = open("mytest.db", "", "", "")
|
||||
## ## do something...
|
||||
## ## db.getAllRows(sql"SELECT * FROM my_table")
|
||||
## db.close()
|
||||
## except:
|
||||
## stderr.writeLine(getCurrentExceptionMsg())
|
||||
## ```
|
||||
var db: DbConn
|
||||
if sqlite3.open(connection, db) == SQLITE_OK:
|
||||
result = db
|
||||
|
||||
@@ -17,37 +17,42 @@
|
||||
##
|
||||
## This is roughly equivalent to the `async` keyword in JavaScript code.
|
||||
##
|
||||
## .. code-block:: nim
|
||||
## proc loadGame(name: string): Future[Game] {.async.} =
|
||||
## # code
|
||||
## ```nim
|
||||
## proc loadGame(name: string): Future[Game] {.async.} =
|
||||
## # code
|
||||
## ```
|
||||
##
|
||||
## should be equivalent to
|
||||
##
|
||||
## .. code-block:: javascript
|
||||
## ```javascript
|
||||
## async function loadGame(name) {
|
||||
## // code
|
||||
## }
|
||||
## ```
|
||||
##
|
||||
## A call to an asynchronous procedure usually needs `await` to wait for
|
||||
## the completion of the `Future`.
|
||||
##
|
||||
## .. code-block:: nim
|
||||
## ```nim
|
||||
## var game = await loadGame(name)
|
||||
## ```
|
||||
##
|
||||
## Often, you might work with callback-based API-s. You can wrap them with
|
||||
## asynchronous procedures using promises and `newPromise`:
|
||||
##
|
||||
## .. code-block:: nim
|
||||
## ```nim
|
||||
## proc loadGame(name: string): Future[Game] =
|
||||
## var promise = newPromise() do (resolve: proc(response: Game)):
|
||||
## cbBasedLoadGame(name) do (game: Game):
|
||||
## resolve(game)
|
||||
## return promise
|
||||
## ```
|
||||
##
|
||||
## Forward definitions work properly, you just need to always add the `{.async.}` pragma:
|
||||
##
|
||||
## .. code-block:: nim
|
||||
## ```nim
|
||||
## proc loadGame(name: string): Future[Game] {.async.}
|
||||
## ```
|
||||
##
|
||||
## JavaScript compatibility
|
||||
## ========================
|
||||
@@ -57,7 +62,7 @@
|
||||
## 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.
|
||||
|
||||
# xxx code-block:: javascript above gives `LanguageXNotSupported` warning.
|
||||
# xxx code: javascript above gives `LanguageXNotSupported` warning.
|
||||
|
||||
when not defined(js) and not defined(nimsuggest):
|
||||
{.fatal: "Module asyncjs is designed to be used with the JavaScript backend.".}
|
||||
|
||||
@@ -1335,9 +1335,10 @@ since (1, 3):
|
||||
## DOM Parser object (defined on browser only, may not be on NodeJS).
|
||||
## * https://developer.mozilla.org/en-US/docs/Web/API/DOMParser
|
||||
##
|
||||
## .. code-block:: nim
|
||||
## ```nim
|
||||
## let prsr = newDomParser()
|
||||
## discard prsr.parseFromString("<html><marquee>Hello World</marquee></html>".cstring, "text/html".cstring)
|
||||
## ```
|
||||
|
||||
DomException* = ref DOMExceptionObj
|
||||
## The DOMException interface represents an abnormal event (called an exception)
|
||||
|
||||
@@ -268,15 +268,14 @@ macro `.()`*(obj: JsObject,
|
||||
## so be careful when using this.)
|
||||
##
|
||||
## Example:
|
||||
##
|
||||
## .. code-block:: nim
|
||||
##
|
||||
## # Let's get back to the console example:
|
||||
## var console {.importc, nodecl.}: JsObject
|
||||
## let res = console.log("I return undefined!")
|
||||
## console.log(res) # This prints undefined, as console.log always returns
|
||||
## # undefined. Thus one has to be careful, when using
|
||||
## # JsObject calls.
|
||||
## ```nim
|
||||
## # Let's get back to the console example:
|
||||
## var console {.importc, nodecl.}: JsObject
|
||||
## let res = console.log("I return undefined!")
|
||||
## console.log(res) # This prints undefined, as console.log always returns
|
||||
## # undefined. Thus one has to be careful, when using
|
||||
## # JsObject calls.
|
||||
## ```
|
||||
var importString: string
|
||||
if validJsName($field):
|
||||
importString = "#." & $field & "(@)"
|
||||
@@ -407,21 +406,20 @@ macro `{}`*(typ: typedesc, xs: varargs[untyped]): auto =
|
||||
##
|
||||
## 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
|
||||
## # 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};".}
|
||||
## 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};".}
|
||||
## ```
|
||||
let a = ident"a"
|
||||
var body = quote do:
|
||||
var `a` {.noinit.}: `typ`
|
||||
@@ -471,24 +469,25 @@ macro bindMethod*(procedure: typed): auto =
|
||||
## Example:
|
||||
##
|
||||
## We want to generate roughly this JavaScript:
|
||||
##
|
||||
## .. code-block:: js
|
||||
## var obj = {a: 10};
|
||||
## obj.someMethod = function() {
|
||||
## return this.a + 42;
|
||||
## };
|
||||
## ```js
|
||||
## var obj = {a: 10};
|
||||
## obj.someMethod = function() {
|
||||
## return this.a + 42;
|
||||
## };
|
||||
## ```
|
||||
##
|
||||
## We can achieve this using the `bindMethod` macro:
|
||||
##
|
||||
## .. code-block:: nim
|
||||
## let obj = JsObject{ a: 10 }
|
||||
## proc someMethodImpl(that: JsObject): int =
|
||||
## that.a.to(int) + 42
|
||||
## obj.someMethod = bindMethod someMethodImpl
|
||||
## ```nim
|
||||
## let obj = JsObject{ a: 10 }
|
||||
## proc someMethodImpl(that: JsObject): int =
|
||||
## that.a.to(int) + 42
|
||||
## obj.someMethod = bindMethod someMethodImpl
|
||||
##
|
||||
## # Alternatively:
|
||||
## obj.someMethod = bindMethod
|
||||
## proc(that: JsObject): int = that.a.to(int) + 42
|
||||
## # Alternatively:
|
||||
## obj.someMethod = bindMethod
|
||||
## proc(that: JsObject): int = that.a.to(int) + 42
|
||||
## ```
|
||||
if not (procedure.kind == nnkSym or procedure.kind == nnkLambda):
|
||||
error("Argument has to be a proc or a symbol corresponding to a proc.")
|
||||
var
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
##
|
||||
## 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"""
|
||||
## var toknizr: GeneralTokenizer
|
||||
## initGeneralTokenizer(toknizr, code)
|
||||
@@ -31,19 +31,20 @@
|
||||
## else:
|
||||
## echo toknizr.kind # All the kinds of tokens can be processed here.
|
||||
## echo substr(code, toknizr.start, toknizr.length + toknizr.start - 1)
|
||||
## ```
|
||||
##
|
||||
## The proc `getSourceLanguage` can get the language `enum` from a string:
|
||||
##
|
||||
## .. code:: Nim
|
||||
## ```Nim
|
||||
## for l in ["C", "c++", "jAvA", "Nim", "c#"]: echo getSourceLanguage(l)
|
||||
## ```
|
||||
##
|
||||
## There is also a `Cmd` pseudo-language supported, which is a simple generic
|
||||
## shell/cmdline tokenizer (UNIX shell/Powershell/Windows Command):
|
||||
## no escaping, no programming language constructs besides variable definition
|
||||
## at the beginning of line. It supports these operators:
|
||||
##
|
||||
## .. code:: Cmd
|
||||
## & && | || ( ) '' "" ; # for comments
|
||||
## ```Cmd
|
||||
## & && | || ( ) '' "" ; # for comments
|
||||
## ```
|
||||
##
|
||||
## Instead of escaping always use quotes like here
|
||||
## `nimgrep --ext:'nim|nims' file.name`:cmd: shows how to input ``|``.
|
||||
|
||||
@@ -153,12 +153,12 @@ proc initRstGenerator*(g: var RstGenerator, target: OutputTarget,
|
||||
##
|
||||
## Example:
|
||||
##
|
||||
## .. code-block:: nim
|
||||
##
|
||||
## ```nim
|
||||
## import packages/docutils/rstgen
|
||||
##
|
||||
## var gen: RstGenerator
|
||||
## gen.initRstGenerator(outHtml, defaultConfig(), "filename", {})
|
||||
## ```
|
||||
g.config = config
|
||||
g.target = target
|
||||
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
|
||||
## ``initRstGenerator`` and parse a rst file with ``rstParse`` from the
|
||||
## `packages/docutils/rst module <rst.html>`_. Example:
|
||||
##
|
||||
## .. code-block:: nim
|
||||
##
|
||||
## ```nim
|
||||
## # ...configure gen and rst vars...
|
||||
## var generatedHtml = ""
|
||||
## renderRstToOut(gen, rst, generatedHtml)
|
||||
## echo generatedHtml
|
||||
## ```
|
||||
|
||||
proc renderAux(d: PDoc, n: PRstNode, result: var string) =
|
||||
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
|
||||
## ``initRstGenerator`` proc. Example:
|
||||
##
|
||||
## .. code-block:: nim
|
||||
## ```nim
|
||||
## import packages/docutils/rstgen, strtabs
|
||||
##
|
||||
## echo rstToHtml("*Hello* **world**!", {},
|
||||
## newStringTable(modeStyleInsensitive))
|
||||
## # --> <em>Hello</em> <strong>world</strong>!
|
||||
## ```
|
||||
##
|
||||
## If you need to allow the rst ``include`` directive or tweak the generated
|
||||
## output you have to create your own ``RstGenerator`` with
|
||||
|
||||
@@ -75,11 +75,11 @@ proc inotify_rm_watch*(fd: cint; wd: cint): cint {.cdecl,
|
||||
|
||||
iterator inotify_events*(evs: pointer, n: int): ptr InotifyEvent =
|
||||
## Abstract the packed buffer interface to yield event object pointers.
|
||||
##
|
||||
## .. code-block:: Nim
|
||||
## ```Nim
|
||||
## var evs = newSeq[byte](8192) # Already did inotify_init+add_watch
|
||||
## 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
|
||||
## ```
|
||||
var ev: ptr InotifyEvent = cast[ptr InotifyEvent](evs)
|
||||
var n = n
|
||||
while n > 0:
|
||||
|
||||
@@ -1093,11 +1093,11 @@ template onSignal*(signals: varargs[cint], body: untyped) =
|
||||
## scope.
|
||||
##
|
||||
## Example:
|
||||
##
|
||||
## .. code-block::
|
||||
## ```Nim
|
||||
## from std/posix import SIGINT, SIGTERM, onSignal
|
||||
## onSignal(SIGINT, SIGTERM):
|
||||
## echo "bye from signal ", sig
|
||||
## ```
|
||||
|
||||
for s in signals:
|
||||
handle_signal(s,
|
||||
|
||||
@@ -379,22 +379,22 @@ func sort*[T](a: var openArray[T],
|
||||
## `cmp`, you may use `system.cmp` or instead call the overloaded
|
||||
## version of `sort`, which uses `system.cmp`.
|
||||
##
|
||||
## .. code-block:: nim
|
||||
##
|
||||
## sort(myIntArray, system.cmp[int])
|
||||
## # do not use cmp[string] here as we want to use the specialized
|
||||
## # overload:
|
||||
## sort(myStrArray, system.cmp)
|
||||
## ```nim
|
||||
## sort(myIntArray, system.cmp[int])
|
||||
## # do not use cmp[string] here as we want to use the specialized
|
||||
## # overload:
|
||||
## sort(myStrArray, system.cmp)
|
||||
## ```
|
||||
##
|
||||
## You can inline adhoc comparison procs with the `do notation
|
||||
## <manual_experimental.html#do-notation>`_. Example:
|
||||
##
|
||||
## .. code-block:: nim
|
||||
##
|
||||
## ```nim
|
||||
## people.sort do (x, y: Person) -> int:
|
||||
## result = cmp(x.surname, y.surname)
|
||||
## if result == 0:
|
||||
## result = cmp(x.name, y.name)
|
||||
## ```
|
||||
##
|
||||
## **See also:**
|
||||
## * `sort proc<#sort,openArray[T]>`_
|
||||
|
||||
@@ -41,13 +41,13 @@
|
||||
## requested amount of data is read **or** an exception occurs.
|
||||
##
|
||||
## Code to read some data from a socket may look something like this:
|
||||
##
|
||||
## .. code-block:: Nim
|
||||
## var future = socket.recv(100)
|
||||
## future.addCallback(
|
||||
## proc () =
|
||||
## echo(future.read)
|
||||
## )
|
||||
## ```Nim
|
||||
## var future = socket.recv(100)
|
||||
## future.addCallback(
|
||||
## proc () =
|
||||
## echo(future.read)
|
||||
## )
|
||||
## ```
|
||||
##
|
||||
## All asynchronous functions returning a `Future` will not block. They
|
||||
## 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;
|
||||
## by using the try statement:
|
||||
##
|
||||
##
|
||||
## .. code-block:: Nim
|
||||
## ```Nim
|
||||
## try:
|
||||
## let data = await sock.recv(100)
|
||||
## echo("Received ", data)
|
||||
## except:
|
||||
## # Handle exception
|
||||
##
|
||||
##
|
||||
## ```
|
||||
##
|
||||
## An alternative approach to handling exceptions is to use `yield` on a future
|
||||
## then check the future's `failed` property. For example:
|
||||
##
|
||||
## .. code-block:: Nim
|
||||
## ```Nim
|
||||
## var future = sock.recv(100)
|
||||
## yield future
|
||||
## if future.failed:
|
||||
## # Handle exception
|
||||
## ```
|
||||
##
|
||||
##
|
||||
## Discarding futures
|
||||
## ==================
|
||||
|
||||
@@ -9,18 +9,19 @@
|
||||
|
||||
## This module implements asynchronous file reading and writing.
|
||||
##
|
||||
## .. code-block:: Nim
|
||||
## import std/[asyncfile, asyncdispatch, os]
|
||||
## ```Nim
|
||||
## import std/[asyncfile, asyncdispatch, os]
|
||||
##
|
||||
## proc main() {.async.} =
|
||||
## var file = openAsync(getTempDir() / "foobar.txt", fmReadWrite)
|
||||
## await file.write("test")
|
||||
## file.setFilePos(0)
|
||||
## let data = await file.readAll()
|
||||
## doAssert data == "test"
|
||||
## file.close()
|
||||
## proc main() {.async.} =
|
||||
## var file = openAsync(getTempDir() / "foobar.txt", fmReadWrite)
|
||||
## await file.write("test")
|
||||
## file.setFilePos(0)
|
||||
## let data = await file.readAll()
|
||||
## doAssert data == "test"
|
||||
## file.close()
|
||||
##
|
||||
## waitFor main()
|
||||
## waitFor main()
|
||||
## ```
|
||||
|
||||
import asyncdispatch, os
|
||||
|
||||
|
||||
@@ -21,13 +21,14 @@
|
||||
## 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.
|
||||
##
|
||||
## .. code-block:: Nim
|
||||
## import std/[asyncdispatch, asyncftpclient]
|
||||
## proc main() {.async.} =
|
||||
## var ftp = newAsyncFtpClient("example.com", user = "test", pass = "test")
|
||||
## await ftp.connect()
|
||||
## echo("Connected")
|
||||
## waitFor(main())
|
||||
## ```Nim
|
||||
## import std/[asyncdispatch, asyncftpclient]
|
||||
## proc main() {.async.} =
|
||||
## var ftp = newAsyncFtpClient("example.com", user = "test", pass = "test")
|
||||
## await ftp.connect()
|
||||
## echo("Connected")
|
||||
## waitFor(main())
|
||||
## ```
|
||||
##
|
||||
## A new `main` async procedure must be declared to allow the use of 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
|
||||
## instead specify an absolute path.
|
||||
##
|
||||
## .. code-block:: Nim
|
||||
## import std/[asyncdispatch, asyncftpclient]
|
||||
## proc main() {.async.} =
|
||||
## var ftp = newAsyncFtpClient("example.com", user = "test", pass = "test")
|
||||
## await ftp.connect()
|
||||
## let currentDir = await ftp.pwd()
|
||||
## assert currentDir == "/home/user/"
|
||||
## await ftp.store("file.txt", "file.txt")
|
||||
## echo("File finished uploading")
|
||||
## waitFor(main())
|
||||
## ```Nim
|
||||
## import std/[asyncdispatch, asyncftpclient]
|
||||
## proc main() {.async.} =
|
||||
## var ftp = newAsyncFtpClient("example.com", user = "test", pass = "test")
|
||||
## await ftp.connect()
|
||||
## let currentDir = await ftp.pwd()
|
||||
## assert currentDir == "/home/user/"
|
||||
## await ftp.store("file.txt", "file.txt")
|
||||
## echo("File finished uploading")
|
||||
## waitFor(main())
|
||||
## ```
|
||||
##
|
||||
## Checking the progress of a file transfer
|
||||
## ========================================
|
||||
@@ -62,20 +64,21 @@
|
||||
## Procs that take an `onProgressChanged` callback will call this every
|
||||
## `progressInterval` milliseconds.
|
||||
##
|
||||
## .. code-block:: Nim
|
||||
## import std/[asyncdispatch, asyncftpclient]
|
||||
## ```Nim
|
||||
## import std/[asyncdispatch, asyncftpclient]
|
||||
##
|
||||
## proc onProgressChanged(total, progress: BiggestInt,
|
||||
## speed: float) {.async.} =
|
||||
## echo("Uploaded ", progress, " of ", total, " bytes")
|
||||
## echo("Current speed: ", speed, " kb/s")
|
||||
## proc onProgressChanged(total, progress: BiggestInt,
|
||||
## speed: float) {.async.} =
|
||||
## echo("Uploaded ", progress, " of ", total, " bytes")
|
||||
## echo("Current speed: ", speed, " kb/s")
|
||||
##
|
||||
## proc main() {.async.} =
|
||||
## var ftp = newAsyncFtpClient("example.com", user = "test", pass = "test", progressInterval = 500)
|
||||
## await ftp.connect()
|
||||
## await ftp.store("file.txt", "/home/user/file.txt", onProgressChanged)
|
||||
## echo("File finished uploading")
|
||||
## waitFor(main())
|
||||
## proc main() {.async.} =
|
||||
## var ftp = newAsyncFtpClient("example.com", user = "test", pass = "test", progressInterval = 500)
|
||||
## await ftp.connect()
|
||||
## await ftp.store("file.txt", "/home/user/file.txt", onProgressChanged)
|
||||
## echo("File finished uploading")
|
||||
## waitFor(main())
|
||||
## ```
|
||||
|
||||
|
||||
import asyncdispatch, asyncnet, nativesockets, strutils, parseutils, os, times
|
||||
|
||||
@@ -65,8 +65,7 @@
|
||||
##
|
||||
## The following example demonstrates a simple chat server.
|
||||
##
|
||||
## .. code-block:: Nim
|
||||
##
|
||||
## ```Nim
|
||||
## import std/[asyncnet, asyncdispatch]
|
||||
##
|
||||
## var clients {.threadvar.}: seq[AsyncSocket]
|
||||
@@ -93,7 +92,7 @@
|
||||
##
|
||||
## asyncCheck serve()
|
||||
## runForever()
|
||||
##
|
||||
## ```
|
||||
|
||||
import std/private/since
|
||||
|
||||
|
||||
@@ -69,8 +69,9 @@ proc openDefaultBrowser*(url: string) =
|
||||
##
|
||||
## This proc doesn't raise an exception on error, beware.
|
||||
##
|
||||
## .. code-block:: nim
|
||||
## ```nim
|
||||
## block: openDefaultBrowser("https://nim-lang.org")
|
||||
## ```
|
||||
doAssert url.len > 0, "URL must not be empty string"
|
||||
openDefaultBrowserImpl(url)
|
||||
|
||||
@@ -85,10 +86,11 @@ proc openDefaultBrowser*() {.since: (1, 1).} =
|
||||
##
|
||||
## This proc doesn't raise an exception on error, beware.
|
||||
##
|
||||
## ```nim
|
||||
## block: openDefaultBrowser()
|
||||
## ```
|
||||
##
|
||||
## **See also:**
|
||||
##
|
||||
## * https://tools.ietf.org/html/rfc6694#section-3
|
||||
##
|
||||
## .. code-block:: nim
|
||||
## block: openDefaultBrowser()
|
||||
openDefaultBrowserImpl("http:about:blank") # See IETF RFC-6694 Section 3.
|
||||
|
||||
@@ -9,25 +9,25 @@
|
||||
|
||||
## 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:
|
||||
## setTestData("name", "Klaus", "password", "123456")
|
||||
## # read the data into `myData`
|
||||
## var myData = readData()
|
||||
## # check that the data's variable names are "name" or "password"
|
||||
## validateData(myData, "name", "password")
|
||||
## # start generating content:
|
||||
## writeContentType()
|
||||
## # generate content:
|
||||
## write(stdout, "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n")
|
||||
## write(stdout, "<html><head><title>Test</title></head><body>\n")
|
||||
## writeLine(stdout, "your name: " & myData["name"])
|
||||
## writeLine(stdout, "your password: " & myData["password"])
|
||||
## writeLine(stdout, "</body></html>")
|
||||
## # Fill the values when debugging:
|
||||
## when debug:
|
||||
## setTestData("name", "Klaus", "password", "123456")
|
||||
## # read the data into `myData`
|
||||
## var myData = readData()
|
||||
## # check that the data's variable names are "name" or "password"
|
||||
## validateData(myData, "name", "password")
|
||||
## # start generating content:
|
||||
## writeContentType()
|
||||
## # generate content:
|
||||
## write(stdout, "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n")
|
||||
## write(stdout, "<html><head><title>Test</title></head><body>\n")
|
||||
## writeLine(stdout, "your name: " & myData["name"])
|
||||
## writeLine(stdout, "your password: " & myData["password"])
|
||||
## writeLine(stdout, "</body></html>")
|
||||
## ```
|
||||
|
||||
import strutils, os, strtabs, cookies, uri
|
||||
export uri.encodeUrl, uri.decodeUrl
|
||||
@@ -252,9 +252,9 @@ proc setTestData*(keysvalues: varargs[string]) =
|
||||
## Fills the appropriate environment variables to test your CGI application.
|
||||
## This can only simulate the 'GET' request method. `keysvalues` should
|
||||
## provide embedded (name, value)-pairs. Example:
|
||||
##
|
||||
## .. code-block:: Nim
|
||||
## setTestData("name", "Hanz", "password", "12345")
|
||||
## ```Nim
|
||||
## setTestData("name", "Hanz", "password", "12345")
|
||||
## ```
|
||||
putEnv("REQUEST_METHOD", "GET")
|
||||
var i = 0
|
||||
var query = ""
|
||||
@@ -269,9 +269,9 @@ proc setTestData*(keysvalues: varargs[string]) =
|
||||
proc writeContentType*() =
|
||||
## Calls this before starting to send your HTML data to `stdout`. This
|
||||
## implements this part of the CGI protocol:
|
||||
##
|
||||
## .. code-block:: Nim
|
||||
## write(stdout, "Content-type: text/html\n\n")
|
||||
## ```Nim
|
||||
## write(stdout, "Content-type: text/html\n\n")
|
||||
## ```
|
||||
write(stdout, "Content-type: text/html\n\n")
|
||||
|
||||
proc resetForStacktrace() =
|
||||
|
||||
Reference in New Issue
Block a user