├── .github └── workflows │ └── tests.yml ├── .gitignore ├── LICENSE ├── README.md ├── c.o ├── config.nims ├── examples ├── client_async.nim ├── config.nims ├── enrich_req.nim └── server_async.nim ├── kdb.nimble ├── src ├── k.c ├── k.h ├── kdb.nim └── kdb │ ├── high.nim │ ├── high │ ├── dict.nim │ ├── ipc │ │ ├── async.nim │ │ ├── shared.nim │ │ └── sync.nim │ ├── sym.nim │ ├── table.nim │ └── vec.nim │ ├── low.nim │ └── low │ ├── access.nim │ ├── bindings.nim │ ├── converters.nim │ ├── format.nim │ ├── ipc.nim │ ├── ipc_async.nim │ ├── iters.nim │ ├── procs.nim │ └── types.nim └── tests ├── basic.nim ├── config.nims ├── extended.nim ├── extended_ipc.nim ├── mem.nim ├── remote.nim ├── test_1_low.nim └── test_2_high.nim /.github/workflows/tests.yml: -------------------------------------------------------------------------------- 1 | name: Tests 2 | 3 | on: [push] 4 | 5 | jobs: 6 | tests: 7 | runs-on: ubuntu-latest 8 | timeout-minutes: 5 9 | strategy: 10 | matrix: 11 | nim: [ 'stable' ] 12 | steps: 13 | - uses: actions/checkout@v2 14 | - name: Cache nimble 15 | id: cache-nimble 16 | uses: actions/cache@v2 17 | with: 18 | path: ~/.nimble 19 | key: ${{ runner.os }}-nimble-${{ matrix.nim }} 20 | - uses: jiro4989/setup-nim-action@v1 21 | with: 22 | nim-version: ${{ matrix.nim }} 23 | # - run: nimble build -Y 24 | - run: nimble test -y 25 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode/settings.json 2 | main 3 | tests/test1 4 | tests/test_1_low 5 | tests/test_2_high 6 | examples/enrich_req 7 | examples/client_async 8 | examples/server_async 9 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Nim to Kdb type-safe bindings 2 | [![](https://github.com/inv2004/kdb_nim/workflows/Tests/badge.svg)](https://github.com/inv2004/kdb_nim/actions?query=workflow%3ATests) 3 | 4 | **Kdb** is a column-oriented database https://kx.com with built-in Q and K languages. It is quite popular for financial and time-series analytics. 5 | 6 | **Nim** is a statically typed compiled programming language with an optional GC https://nim-lang.org. It compiles to very efficient C code, that is why its' speed is often near or equals the vanilla-C implementation. In addition Nim shares a lot of Python-like aspects like syntax and simplicity of usage. 7 | 8 | ### Reason 9 | The goal of this package is not only to provide bindings between the two languages, but to build statically-checked code and structures on top of Kdb, which, due to it's duck-typed nature leads to a lot of exceptions and runtime errors in Kdb projects. 10 | 11 | ### Features / TODO: 12 | - [x] Support all Kdb types in low-level binding 13 | - [x] Automatic memory management 14 | - [x] IPC + Sync Reply 15 | - [x] Implicit casting between Nim and Kdb types 16 | - [x] Iterators and mutable iterators 17 | - [x] Separate types for static garanties 18 | - [x] Generic types for K-structures 19 | - [x] Async-await IO/IPC dispatching 20 | - [x] IPC Routing macro 21 | - [ ] Native implementation without k bindings 22 | - [ ] Historical files access 23 | - [ ] Translate the package into Java/Scala/Kotlin/Rust (by request) 24 | 25 | ### Advantages 26 | Except low-level binding from ``kdb/low``, the main goal the library to interact via high-level type-checked interface. 27 | The best way to understand the advantages of this package is by going through an example: 28 | 29 | #### Init part 30 | **updated to async** 31 | 32 | Code to run on q-server side to simulate stream data after some-kind of subscription: 33 | ```kdb 34 | .u.sub:{[x;y;z] system"t 1000"; .z.ts:{[x;y] -1 .Q.s2 x(`enrich;([] n:10?5))}[.z.w]; (1b; `ok)} 35 | ``` 36 | 37 | Full code is here [enrich_req.nim](/examples/enrich_req.nim) 38 | 39 | Nim-client: 40 | ```nim 41 | type 42 | RequestT = object of RootObj 43 | n: int 44 | 45 | ReplyT = object of RequestT 46 | s: Sym 47 | 48 | defineTable(RequestT) 49 | defineTable(ReplyT) 50 | ``` 51 | One of the main ideas of the library is to help to catch all type-related errors during compile time. That's why the first thing we want is to define schema for the tables we use. We generate the schema by ``defineTable`` declaration from basic language structures which represent a row of our table. 52 | 53 | Another point is that Nim has inheritance for structures, and we can use it, so the table ``ReplyT`` actually has two fields: ``s`` and ``n`` from ``RequestT``. 54 | 55 | ``defineTable`` automatically generates a functions to interact with the table according to the struct's fields and types during compiletime, not runtime. 56 | 57 | ```nim 58 | let client = waitFor asyncConnect("your-server", 9999) 59 | 60 | let rep = waitFor client.asyncCall[:(bool, Sym)](".u.sub", 123.456, "str", s"sym") 61 | echo rep 62 | ``` 63 | I would like to point out that we provide a type for call function - and it converts the reply from kdb-side into the provided type if possible. Also, we have implicit converter from nim-types into kdb-structures, so we put most of the types into the function arguments without conversion. 64 | 65 | There is also a ``Sym`` type with an ``s`` constructor to easily distinguish sym from string kdb-types, but if you have Sym in the table, functions like add or transform will implicitly convert string into Sym 66 | 67 | #### Main part 68 | 69 | ```nim 70 | serve(client): 71 | proc enrich(data: KTable[RequestT]): KTable[ReplyT] = 72 | ``` 73 | The serve macros generate simple routing for IPC-calls. So, if external server or client will call ``enrich`` procedure on the process - it will find definition provided in ``serve`` block and will call it. Also, the function can check that the data received from kdb-side matches the scheme for the table we defined and throw an exception otherwise. 74 | 75 | ```nim 76 | let symCol = data.n.mapIt(d.getOrDefault(it)) 77 | ``` 78 | Here we generate a new column for our reply, see how we can access table's fields (``n`` here) and if we made a mistake and typed ``nn`` then we would've had a compilation error: ``Error: undeclared field: 'nn'``. 79 | 80 | ```nim 81 | result = data.transform(ReplyT, symCol) 82 | ``` 83 | ``transform`` function was made to transform tables from one schema to another. By default it makes in-place transformation, so we do not copy the data, but internally enrich low-level kdb data with the new columns or delete some if necessary. We do not need old ``data`` anymore, ``data`` is not available after this transformation. So, to transform ``RequestT`` into ``ReplyT`` we have to add one more column and we provide it in the argument to the function. If ``transform`` does not have arguments except the type, then the column is created with default values for the column's type. 84 | 85 | It's important point out that we also do type checking here. If we try to put floats into the Sym column for some reasons, we will get a compilation error: ``Error: transform error: expected: Sym, provided: float`` 86 | 87 | ```nim 88 | result.add(ReplyT(n: 100, s: "hundred")) 89 | echo result 90 | ``` 91 | Nim distinguishes between mutable and immutable data, by default result of the procedure is mutable, and it helps us because we are going to modify it by adding row. If we provided a wrong struct or types into the ``add`` function then we would get compilation error, I specifically mentioned this because in kdb the problem can only be found at runtime or even in production. 92 | 93 | Additional point that the library automatically detects is it sync or async call and sends reply back according to the requested message type, but it does not block thread in any case, because all logic is implemented in Nim's asynchronous IO. 94 | 95 | All types implement the output interface, so you will see a reply after ``echo`` 96 | ```nim 97 | ┌─────┬─────────┐ 98 | │ n │ s │ 99 | ├─────┼─────────┤ 100 | │ 2 │ two │ 101 | │ 4 │ │ 102 | │ 3 │ three │ 103 | . . . 104 | │ 100 │ hundred │ 105 | └─────┴─────────┘ 106 | ```` 107 | 108 | ```nim 109 | runForever() 110 | ``` 111 | The lib supports asyncdispatch module of the Nim language, that is why we start main event loop here. 112 | 113 | -------------------------------------------------------------------------------- /c.o: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/inv2004/kdb_nim/2fbc9da70a508c27ca6da81d28c6e5ea79a4f030/c.o -------------------------------------------------------------------------------- /config.nims: -------------------------------------------------------------------------------- 1 | switch("threads", "on") 2 | switch("sinkInference", "off") -------------------------------------------------------------------------------- /examples/client_async.nim: -------------------------------------------------------------------------------- 1 | import kdb, asyncdispatch 2 | 3 | proc test(x: string): string = 4 | "> " & x & "\c\L" 5 | 6 | asyncCheck asyncServe(9999, test) 7 | runForever() 8 | -------------------------------------------------------------------------------- /examples/config.nims: -------------------------------------------------------------------------------- 1 | switch("path", "$projectDir/../src") -------------------------------------------------------------------------------- /examples/enrich_req.nim: -------------------------------------------------------------------------------- 1 | import kdb 2 | import sequtils 3 | import tables 4 | import asyncdispatch 5 | 6 | type 7 | RequestT = object of RootObj 8 | n: int 9 | 10 | ReplyT = object of RequestT 11 | s: Sym 12 | 13 | defineTable(RequestT) 14 | defineTable(ReplyT) 15 | 16 | # q-server: 17 | # .u.sub:{[x;y;z] system"t 1000"; .z.ts:{[x;y] -1 .Q.s2 x(`enrich;([] n:10?5))}[.z.w]; (1b; `ok)} 18 | 19 | let client = waitFor asyncConnect("your-server", 9999) 20 | 21 | let rep = waitFor client.asyncCall[:(bool, Sym)](".u.sub", 123.456, "str", s"sym") 22 | echo rep 23 | 24 | serve(client): 25 | proc enrich(data: KTable[RequestT]): KTable[ReplyT] = 26 | let newCol = data.n.mapIt(d.getOrDefault(it)) 27 | result = data.transform(ReplyT, newCol) 28 | result.add(ReplyT(n: 100, s: "hundred")) 29 | echo result 30 | 31 | runForever() 32 | -------------------------------------------------------------------------------- /examples/server_async.nim: -------------------------------------------------------------------------------- 1 | import kdb 2 | import asyncdispatch 3 | 4 | type 5 | ReqT = object 6 | x: int64 7 | ResT = object 8 | x: float64 9 | 10 | defineTable(ReqT) 11 | defineTable(ResT) 12 | 13 | serve(9000): 14 | proc f1(x: KTable[ReqT]): KTable[ResT] {.gcsafe.} = 15 | result = newKTable(ResT) 16 | for x in x.x: 17 | result.add(ResT(x: 11 * x.float + x.float / 10.0)) 18 | 19 | proc f2(x: KTable[ResT]): KTable[ReqT] {.gcsafe.} = 20 | result = newKTable(ReqT) 21 | for x in x.x: 22 | result.add(ReqT(x: 11 * x.int64)) 23 | 24 | proc send1() {.async.} = 25 | let h = waitFor asyncConnect("localhost", 9000) 26 | var t = newKTable(ReqT) 27 | t.add(ReqT(x: 1)) 28 | t.add(ReqT(x: 2)) 29 | t.add(ReqT(x: 3)) 30 | let response = waitFor h.callTable[:ReqT, ResT]("f1", t, check = true) 31 | echo response 32 | 33 | proc send2() {.async.} = 34 | let h = waitFor asyncConnect("localhost", 9000) 35 | var t = newKTable(ResT) 36 | t.add(ResT(x: 1)) 37 | t.add(ResT(x: 2)) 38 | t.add(ResT(x: 3)) 39 | let response = waitFor h.callTable[:ResT, ReqT]("f2", t, check = true) 40 | echo response 41 | 42 | waitFor send1() 43 | waitFor send2() 44 | 45 | runForever() -------------------------------------------------------------------------------- /kdb.nimble: -------------------------------------------------------------------------------- 1 | # Package 2 | 3 | version = "0.7.0" 4 | author = "inv2004" 5 | description = "Nim structs to work with Kdb in type-safe manner and low-level Nim to Kdb bindings" 6 | license = "Apache-2.0" 7 | srcDir = "src" 8 | 9 | # bin = @["main"] 10 | 11 | # Dependencies 12 | 13 | requires "nim >= 1.2.0" 14 | requires "terminaltables >= 0.1.1" 15 | requires "uuids >= 0.1.10" 16 | -------------------------------------------------------------------------------- /src/k.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include "k.h" 3 | 4 | K km(int months) { 5 | K k = ki(months); 6 | k->t = -KM; 7 | return k; 8 | } 9 | 10 | K kmi(int minutes) { 11 | K k = ki(minutes); 12 | k->t = -KU; 13 | return k; 14 | } 15 | 16 | K kse(int seconds) { 17 | K k = ki(seconds); 18 | k->t = -KV; 19 | return k; 20 | } 21 | 22 | K kerr(char* x) { 23 | K k = ks(x); 24 | k->t = -128; 25 | return k; 26 | } 27 | 28 | void check_c_struct_offset() { 29 | printf("C-struct-offset:\n"); 30 | printf(" m: %ld\n", offsetof(struct k0, m)); 31 | printf(" a: %ld\n", offsetof(struct k0, a)); 32 | printf(" t: %ld\n", offsetof(struct k0, t)); 33 | printf(" u: %ld\n", offsetof(struct k0, u)); 34 | printf(" r: %ld\n", offsetof(struct k0, r)); 35 | printf(" k: %ld\n", offsetof(struct k0, k)); 36 | printf(" n: %ld\n", offsetof(struct k0, n)); 37 | printf(" g0: %ld\n", offsetof(struct k0, G0)); 38 | } 39 | -------------------------------------------------------------------------------- /src/k.h: -------------------------------------------------------------------------------- 1 | #ifndef KX 2 | #define KX 3 | typedef char*S,C;typedef unsigned char G;typedef short H;typedef int I;typedef long long J;typedef float E;typedef double F;typedef void V; 4 | #ifdef __cplusplus 5 | extern"C"{ 6 | #endif 7 | #if !defined(KXVER) 8 | #error "Set KXVER=3 for kdb+3.0 or standalone c-api after 2011-04-20. Otherwise set KXVER=2. e.g. #define KXVER 3 or gcc -DKXVER=3" 9 | #endif 10 | #if KXVER>=3 11 | typedef struct k0{signed char m,a,t;C u;I r;union{G g;H h;I i;J j;E e;F f;S s;struct k0*k;struct{J n;G G0[1];};};}*K; 12 | typedef struct{G g[16];}U; 13 | #define kU(x) ((U*)kG(x)) 14 | #define xU ((U*)xG) 15 | extern K ku(U),knt(J,K),ktn(I,J),kpn(S,J); 16 | extern I setm(I),ver(); 17 | #define DO(n,x) {J i=0,_i=(n);for(;i<_i;++i){x;}} 18 | #else 19 | typedef struct k0{I r;H t,u;union{G g;H h;I i;J j;E e;F f;S s;struct k0*k;struct{I n;G G0[1];};};}*K; 20 | extern K ktn(I,I),kpn(S,I); 21 | #define DO(n,x) {I i=0,_i=(n);for(;i<_i;++i){x;}} 22 | #endif 23 | #ifdef __cplusplus 24 | } 25 | #endif 26 | //#include 27 | // vector accessors, e.g. kF(x)[i] for float&datetime 28 | #define kG(x) ((x)->G0) 29 | #define kC(x) kG(x) 30 | #define kH(x) ((H*)kG(x)) 31 | #define kI(x) ((I*)kG(x)) 32 | #define kJ(x) ((J*)kG(x)) 33 | #define kE(x) ((E*)kG(x)) 34 | #define kF(x) ((F*)kG(x)) 35 | #define kS(x) ((S*)kG(x)) 36 | #define kK(x) ((K*)kG(x)) 37 | 38 | // type bytes qtype ctype accessor 39 | #define KB 1 // 1 boolean char kG 40 | #define UU 2 // 16 guid U kU 41 | #define KG 4 // 1 byte char kG 42 | #define KH 5 // 2 short short kH 43 | #define KI 6 // 4 int int kI 44 | #define KJ 7 // 8 long long kJ 45 | #define KE 8 // 4 real float kE 46 | #define KF 9 // 8 float double kF 47 | #define KC 10 // 1 char char kC 48 | #define KS 11 // * symbol char* kS 49 | 50 | #define KP 12 // 8 timestamp long kJ (nanoseconds from 2000.01.01) 51 | #define KM 13 // 4 month int kI (months from 2000.01.01) 52 | #define KD 14 // 4 date int kI (days from 2000.01.01) 53 | 54 | #define KN 16 // 8 timespan long kJ (nanoseconds) 55 | #define KU 17 // 4 minute int kI 56 | #define KV 18 // 4 second int kI 57 | #define KT 19 // 4 time int kI (millisecond) 58 | 59 | #define KZ 15 // 8 datetime double kF (DO NOT USE) 60 | 61 | // table,dict 62 | #define XT 98 // x->k is XD 63 | #define XD 99 // kK(x)[0] is keys. kK(x)[1] is values. 64 | 65 | #ifdef __cplusplus 66 | #include 67 | extern"C"{ 68 | extern V m9(); 69 | #else 70 | #include 71 | extern V m9(V); 72 | #endif 73 | extern I khpunc(S,I,S,I,I),khpun(const S,I,const S,I),khpu(const S,I,const S),khp(const S,I),okx(K),ymd(I,I,I),dj(I);extern V r0(K),sd0(I),sd0x(I d,I f),kclose(I);extern S sn(S,I),ss(S); 74 | extern K ee(K),ktj(I,J),ka(I),kb(I),kg(I),kh(I),ki(I),kj(J),ke(F),kf(F),kc(I),ks(S),kd(I),kz(F),kt(I),sd1(I,K(*)(I)),dl(V*f,J), 75 | knk(I,...),kp(S),ja(K*,V*),js(K*,S),jk(K*,K),jv(K*k,K),k(I,const S,...),xT(K),xD(K,K),ktd(K),r1(K),krr(const S),orr(const S),dot(K,K),b9(I,K),d9(K),sslInfo(K x),vaknk(I,va_list),vak(I,const S,va_list); 76 | #ifdef __cplusplus 77 | } 78 | #endif 79 | 80 | // nulls(n?) and infinities(w?) 81 | #define nh ((I)0xFFFF8000) 82 | #define wh ((I)0x7FFF) 83 | #define ni ((I)0x80000000) 84 | #define wi ((I)0x7FFFFFFF) 85 | #define nj ((J)0x8000000000000000LL) 86 | #define wj 0x7FFFFFFFFFFFFFFFLL 87 | #if defined(WIN32) || defined(_WIN32) 88 | #define nf (log(-1.0)) 89 | #define wf (-log(0.0)) 90 | #define finite _finite 91 | extern double log(double); 92 | #else 93 | #define nf (0/0.0) 94 | #define wf (1/0.0) 95 | #define closesocket(x) close(x) 96 | #endif 97 | 98 | // remove more clutter 99 | #define O printf 100 | #define R return 101 | #define Z static 102 | #define P(x,y) {if(x)R(y);} 103 | #define U(x) P(!(x),0) 104 | #define SW switch 105 | #define CS(n,x) case n:x;break; 106 | #define CD default 107 | 108 | #define ZV Z V 109 | #define ZK Z K 110 | #define ZH Z H 111 | #define ZI Z I 112 | #define ZJ Z J 113 | #define ZE Z E 114 | #define ZF Z F 115 | #define ZC Z C 116 | #define ZS Z S 117 | 118 | #define K1(f) K f(K x) 119 | #define K2(f) K f(K x,K y) 120 | #define TX(T,x) (*(T*)((G*)(x)+8)) 121 | #define xr x->r 122 | #define xt x->t 123 | #define xu x->u 124 | #define xn x->n 125 | #define xx xK[0] 126 | #define xy xK[1] 127 | #define xg TX(G,x) 128 | #define xh TX(H,x) 129 | #define xi TX(I,x) 130 | #define xj TX(J,x) 131 | #define xe TX(E,x) 132 | #define xf TX(F,x) 133 | #define xs TX(S,x) 134 | #define xk TX(K,x) 135 | #define xG x->G0 136 | #define xH ((H*)xG) 137 | #define xI ((I*)xG) 138 | #define xJ ((J*)xG) 139 | #define xE ((E*)xG) 140 | #define xF ((F*)xG) 141 | #define xS ((S*)xG) 142 | #define xK ((K*)xG) 143 | #define xC xG 144 | #define xB ((G*)xG) 145 | 146 | #endif 147 | 148 | -------------------------------------------------------------------------------- /src/kdb.nim: -------------------------------------------------------------------------------- 1 | import kdb/high 2 | export high 3 | 4 | -------------------------------------------------------------------------------- /src/kdb/high.nim: -------------------------------------------------------------------------------- 1 | import kdb/high/vec 2 | export vec 3 | import kdb/high/dict 4 | export dict 5 | import kdb/high/table 6 | export table 7 | import kdb/high/sym 8 | export sym 9 | import kdb/high/ipc/sync 10 | export sync 11 | import kdb/high/ipc/async 12 | export async 13 | -------------------------------------------------------------------------------- /src/kdb/high/dict.nim: -------------------------------------------------------------------------------- 1 | import kdb/low 2 | 3 | type 4 | KDict*[T, U] = object 5 | inner*: K 6 | 7 | proc newKDict*[T, U](): KDict[T, U] = 8 | let kDict = low.newKDict[T, U]() 9 | KDict[T, U](inner: kDict) 10 | 11 | proc `$`*(v: KDict): string = 12 | $v.inner 13 | 14 | proc `[]=`*[T, U](x: var KDict[T, U], k: T, v: U) = 15 | x.inner[k] = %v 16 | 17 | proc `[]`*[T, U](x: KDict[T, U], k: T): U = 18 | x.inner.getDict[:T, U](k) 19 | 20 | -------------------------------------------------------------------------------- /src/kdb/high/ipc/async.nim: -------------------------------------------------------------------------------- 1 | import kdb/low 2 | export low.asyncConnect 3 | export low.KErrorRemote 4 | import kdb/high/table 5 | 6 | import shared 7 | 8 | import asyncnet, asyncdispatch 9 | import endians 10 | 11 | import macros 12 | 13 | var defaultCheck = false 14 | 15 | proc setCheck*(check: bool) = 16 | defaultCheck = check 17 | 18 | proc asyncCallTable*[T,U](client: AsyncSocket, x: string, t: KTable[T], check = defaultCheck): Future[KTable[U]] {.async.} = 19 | let k = await client.asyncCall(x, t.inner) 20 | result = k.toKTable(U, check) 21 | 22 | proc processMessage1(client: AsyncSocket, process: proc (n: string, k: K): K {.gcsafe,closure.}) {.async.} = 23 | let (msgType, k) = await client.readMessage() 24 | 25 | assert isCall(k) 26 | 27 | let fnName = k[0].getStr() 28 | 29 | let reply = process(fnName, k[1].toK()) 30 | 31 | case msgType 32 | of Async: await client.sendASyncAsync(reply) # initial request was async 33 | of Sync: await client.sendSyncReplyAsync(reply) # initial request was sync 34 | else: raise newException(KError, "unsupported msg type: " & $msgType) 35 | 36 | proc processClient(client: AsyncSocket, handshake: bool, process: proc (n: string, k: K): K {.gcsafe,closure.}, oneshot: bool) {.async, gcsafe.} = 37 | if handshake: 38 | await handshake(client) 39 | while true: 40 | await processMessage1(client, process) 41 | if oneshot: 42 | break 43 | 44 | proc asyncServe*(client: AsyncSocket, process: proc (n: string, k: K): K {.gcsafe,closure.}, oneshot: bool) {.async, gcsafe.} = 45 | # asyncCheck processClient(client, false, process) 46 | await processClient(client, false, process, oneshot) 47 | 48 | proc asyncServe*(port: uint32, process: proc (n: string, k: K): K {.gcsafe,closure.}, oneshot: bool) {.async, gcsafe.} = 49 | var server = newAsyncSocket() 50 | server.setSockOpt(OptReuseAddr, true) 51 | server.bindAddr(Port(port)) 52 | server.listen() 53 | echo "serve ", port 54 | while true: 55 | let client = await server.accept() 56 | asyncCheck processClient(client, true, process, oneshot) 57 | 58 | proc getDefs(t: NimNode): seq[(string, NimNode)] = 59 | if t.kind == nnkStmtList: 60 | for x in t: 61 | assert x.kind == nnkProcDef 62 | let name = x[0].strVal 63 | assert x[3].len == 2 # only one input param to function 64 | assert x[3][1].kind == nnkIdentDefs 65 | assert x[3][1][1].kind == nnkBracketExpr 66 | assert x[3][1][1][0].kind == nnkSym 67 | assert x[3][1][1][0].strVal == "KTable" # param is KTable 68 | let ttype = x[3][1][1][1] 69 | result.add (name, ttype) 70 | elif t.kind == nnkProcDef: 71 | let name = t[0].strVal 72 | assert t[3].len == 2 # only one input param to function 73 | assert t[3][1].kind == nnkIdentDefs 74 | assert t[3][1][1].kind == nnkBracketExpr 75 | assert t[3][1][1][0].kind == nnkSym 76 | assert t[3][1][1][0].strVal == "KTable" # param is KTable 77 | let ttype = t[3][1][1][1] 78 | result.add (name, ttype) 79 | 80 | proc newCaseStmt(x: NimNode): NimNode = 81 | result = newNimNode(nnkCaseStmt) 82 | result.add x 83 | 84 | proc newOfBranch(x: NimNode, b: NimNode): NimNode = 85 | result = newNimNode(nnkOfBranch) 86 | result.add x 87 | result.add b 88 | 89 | proc newElse(body: NimNode): NimNode = 90 | result = newNimNode(nnkElse) 91 | result.add body 92 | 93 | proc newRaiseStmt(body: NimNode): NimNode = 94 | result = newNimNode(nnkRaiseStmt) 95 | result.add body 96 | 97 | proc newInfix(x, y, z: NimNode): NimNode = 98 | result = newNimNode(nnkInfix) 99 | result.add x 100 | result.add y 101 | result.add y 102 | 103 | proc newPragma(x: varargs[NimNode]): NimNode = 104 | result = newNimNode(nnkPragma) 105 | result.add x 106 | 107 | macro serve*(port: uint32 | AsyncSocket, body: typed): untyped = 108 | result = newStmtList() 109 | 110 | if body.kind == nnkStmtList: 111 | for x in body: 112 | result.add x 113 | elif body.kind == nnkProcDef: 114 | result.add body 115 | 116 | let defs = getDefs(body) 117 | 118 | let kType = bindSym("K") 119 | let kError = bindSym("KError") 120 | 121 | var params = newSeq[NimNode]() 122 | params.add kType 123 | params.add newIdentDefs(ident "n", ident "string") 124 | params.add newIdentDefs(ident "k", kType) 125 | 126 | var ccase = newCaseStmt(ident "n") 127 | 128 | for (n, t) in defs: 129 | ccase.add newOfBranch(newStrLitNode(n), newStmtList(newDotExpr(newCall(ident n, newCall(newDotExpr(ident"k", ident"toKTable"), t)), ident"inner"))) 130 | ccase.add newElse(newStmtList(newRaiseStmt(newCall(ident"newException", ident"ValueError", newInfix(ident"&", newStrLitNode"function call not found", ident "n"))))) 131 | 132 | result.add newProc(ident("process123"), params, newStmtList(ccase), pragmas = newPragma(ident"gcsafe")) 133 | 134 | result.add quote do: 135 | asyncCheck asyncServe(`port`, process123, false) 136 | 137 | macro serveOne*(port: uint32 | AsyncSocket, body: typed): untyped = 138 | result = newStmtList() 139 | 140 | if body.kind == nnkStmtList: 141 | for x in body: 142 | result.add x 143 | elif body.kind == nnkProcDef: 144 | result.add body 145 | 146 | let defs = getDefs(body) 147 | 148 | let kType = bindSym("K") 149 | let kError = bindSym("KError") 150 | let toKError = bindSym("toKError") 151 | 152 | var params = newSeq[NimNode]() 153 | params.add kType 154 | params.add newIdentDefs(ident "n", ident "string") 155 | params.add newIdentDefs(ident "k", kType) 156 | 157 | var ccase = newCaseStmt(ident "n") 158 | 159 | for (n, t) in defs: 160 | ccase.add newOfBranch(newStrLitNode(n), newStmtList(newDotExpr(newCall(ident n, newCall(newDotExpr(ident"k", ident"toKTable"), t)), ident"inner"))) 161 | ccase.add newElse(newStmtList(newCall(toKError, ident"n"))) 162 | 163 | result.add newProc(ident("process123"), params, newStmtList(ccase), pragmas = newPragma(ident"gcsafe")) 164 | 165 | result.add quote do: 166 | waitFor asyncServe(`port`, process123, true) 167 | 168 | proc asyncCall*[T](socket: AsyncSocket, x: string, a, b, c: K): Future[T] {.async.} = 169 | var l = newKList() 170 | l.add(x.toK()) 171 | # for x in args: 172 | # l.add(x) 173 | l.add(a) 174 | l.add(b) 175 | l.add(c) 176 | 177 | let data = b9(3, l.k) 178 | data.byteArr[1] = 1 # sync type 179 | await socket.send(data.byteArr.addr, data.byteLen.int) 180 | r0(data) 181 | let k = await socket.asyncRead() 182 | result = get[T](k) 183 | 184 | converter toKK*(x: float64): K = 185 | low.toK(x) 186 | 187 | converter toKK*(x: string): K = 188 | low.toK(x) 189 | 190 | converter toKK*(x: Sym): K = 191 | x.inner -------------------------------------------------------------------------------- /src/kdb/high/ipc/shared.nim: -------------------------------------------------------------------------------- 1 | import kdb/low 2 | 3 | proc get*[T](x: K): T = 4 | # assert x.kind == typeToKKind[T]() 5 | when T is bool: 6 | x.k.bb 7 | elif T is int64: 8 | x.k.ii 9 | elif T is int: 10 | x.k.ii 11 | elif T is float: 12 | x.k.ff 13 | elif T is seq[bool]: 14 | result.add toOpenArray(x.k.boolArr.addr, 0, x.k.boolLen.int - 1) 15 | elif T is seq[int64]: 16 | result.add toOpenArray(x.k.longArr.addr, 0, x.k.longLen.int - 1) 17 | elif T is seq[int]: 18 | result.add toOpenArray(x.k.longArr.addr, 0, x.k.longLen.int - 1) 19 | elif T is seq[float]: 20 | result.add toOpenArray(x.k.floatArr.addr, 0, x.k.floatLen.int - 1) 21 | elif T is (bool, Sym): # TODO: remake to support tuple 22 | (x.k.kArr[0].bb, newSym($x.k.kArr[1].ss)) 23 | elif T is (bool, string): # TODO: remake to support tuple 24 | (x.k.kArr[0].bb, $x.k.kArr[1].ss) 25 | else: raise newException(KError, "get[T] is not supported for " & $T) 26 | 27 | -------------------------------------------------------------------------------- /src/kdb/high/ipc/sync.nim: -------------------------------------------------------------------------------- 1 | import kdb/low 2 | export low.listen 3 | export low.connect 4 | import kdb/high/table 5 | 6 | import shared 7 | 8 | import net 9 | 10 | var defaultCheck = false 11 | 12 | proc setCheck*(check: bool) = 13 | defaultCheck = check 14 | 15 | proc read*(client: SocketHandle, T: typedesc, check = defaultCheck): (string, KTable[T]) = 16 | let d = low.read(client) 17 | if not isCall(d): 18 | raise newException(KErrorRemote, "not a ipc call") 19 | 20 | (d[0].getStr(), d[1].toKTable(T, check = check)) 21 | 22 | proc reply*(client: SocketHandle, x: KTable) = 23 | low.sendSyncReply(client, x.inner) 24 | 25 | proc call*[T](client: SocketHandle, x: string, t: KTable): T = 26 | get[T](low.exec(client, x, t.inner)) 27 | 28 | proc callTable*[T](client: SocketHandle, x: string, args: varargs[K, toK], check = defaultCheck): KTable[T] = 29 | let res = low.exec(client, x, args) 30 | res.toKTable(T, check) 31 | 32 | proc call*[T](client: SocketHandle, x: string, args: varargs[K, toK]): T = 33 | get[T](low.exec(client, x, args)) 34 | 35 | proc callAsync*(client: SocketHandle, x: string, args: varargs[K, toK]) = 36 | low.execAsync(client, x, args) 37 | 38 | template toK*(x: typed): K = # TODO: not sure, but varargs wants it 39 | low.toK(x) -------------------------------------------------------------------------------- /src/kdb/high/sym.nim: -------------------------------------------------------------------------------- 1 | import kdb/low 2 | import sequtils 3 | 4 | export Sym 5 | # type 6 | # Sym* = string 7 | 8 | proc newSym*(x: string): Sym = 9 | Sym(inner: x.toSym()) 10 | 11 | proc `s`*(x: string): Sym = 12 | newSym(x) 13 | 14 | proc `$`*(x: Sym): string = 15 | $x.inner 16 | 17 | proc `==`*(a, b: Sym): bool = 18 | a.inner == b.inner 19 | 20 | converter toSymNotLow*(x: string): Sym = 21 | newSym(x) 22 | -------------------------------------------------------------------------------- /src/kdb/high/table.nim: -------------------------------------------------------------------------------- 1 | import kdb/low 2 | import kdb/high/vec 3 | 4 | import kdb/high/sym 5 | 6 | import sequtils 7 | import macros 8 | 9 | type 10 | KTable*[T] = ref object 11 | inner*: K 12 | moved: bool 13 | 14 | proc stringToKVecKind*(x: string): KKind = 15 | case x 16 | of "bool": KKind.kVecBool 17 | of "GUID": KKind.kVecGUID 18 | of "byte": KKind.kVecByte 19 | of "int16": KKind.kVecShort 20 | of "int32": KKind.kVecInt 21 | of "int": KKind.kVecLong 22 | of "int64": KKind.kVecLong 23 | of "float32": KKind.kVecReal 24 | of "float64": KKind.kVecFloat 25 | of "float": KKind.kVecFloat 26 | of "Sym": KKind.kVecSym 27 | of "KTimestamp": KKind.kVecTimestamp 28 | of "KDateTime": KKind.kVecDateTime 29 | of "DateTime": KKind.kVecDateTime 30 | of "KList": KKind.kList 31 | of "string": KKind.kList 32 | of "nil": KKind.kList 33 | else: raise newException(KError, "cannot convert type " & x) 34 | 35 | proc checkMoved(t: KTable) = 36 | if t.moved: raise newException(ValueError, "table has been transformed already") 37 | 38 | proc len*(t: KTable): int = 39 | checkMoved(t) 40 | t.inner.len 41 | 42 | proc cols*(t: KTable): seq[string] = 43 | t.inner.cols 44 | 45 | proc `$`*(t: KTable): string = 46 | checkMoved(t) 47 | $t.inner 48 | 49 | proc getFieldsRec(t: NimNode): seq[(string, string)] = 50 | let obj = getImpl(t)[2] 51 | 52 | if obj[1].kind != nnkEmpty: 53 | result.add getFieldsRec(obj[1][0]) 54 | 55 | let typeFields = obj[2] 56 | 57 | for f in typeFields.children: 58 | assert f.kind == nnkIdentDefs 59 | var fieldNames = newSeq[string]() 60 | for ff in f.children: 61 | case ff.kind 62 | of nnkIdent: fieldNames.add ff.strVal 63 | of nnkSym: 64 | for x in fieldNames: 65 | result.add (x, ff.strVal) 66 | of nnkEmpty: discard 67 | else: raise newException(Exception, "unexpected construction: " & $ff.treeRepr) 68 | 69 | proc calcToAdd[T: KKind | string](f: seq[(string, T)], t: seq[(string, T)]): seq[(string, T)] = 70 | for (x, k) in t: # TODO: something wrong with sets module 71 | var found = false 72 | for (xx, kk) in f: 73 | if x == xx: 74 | if k != kk: 75 | raise newException(Exception, "transfer: type diff") 76 | found = true 77 | break 78 | if not found: 79 | # echo "add2: ", x, ": ", k 80 | result.add((x, k)) 81 | 82 | proc calcToDelete[T: KKind | string](f: seq[(string, T)], t: seq[(string, T)]): seq[string] = 83 | for (x, k) in f: 84 | var found = false 85 | for (xx, kk) in t: 86 | if x == xx: 87 | found = true 88 | break 89 | if not found: 90 | # echo "delete: ", x 91 | result.add(x) 92 | 93 | proc newBracketExpr(a, b: NimNode): NimNode = 94 | result = newNimNode(nnkBracketExpr) 95 | result.add a 96 | result.add b 97 | 98 | proc newDiscardStmt(x: NimNode): NimNode = 99 | result = newNimNode(nnkDiscardStmt) 100 | result.add x 101 | 102 | proc newCommand(a, b: NimNode): NimNode = 103 | result = newNimNode(nnkCommand) 104 | result.add a 105 | result.add b 106 | 107 | macro defineTable*(T: typedesc): untyped = 108 | let fields = getFieldsRec(getType(T)[1]) 109 | 110 | result = newStmtList() 111 | 112 | let getFunc = bindSym("get") 113 | let r1Func = bindSym("r1") 114 | let toKFunc = bindSym("toK") 115 | let kType = bindSym("K") 116 | 117 | let typeDefId = ident($T) 118 | 119 | for i, (x, t) in fields: 120 | let xId = ident(x) 121 | let tId = ident(t) 122 | let iId = newIntLitNode(i) 123 | 124 | result.add quote do: 125 | proc `xId`*(t: KTable[`typeDefId`]): KVec[`tId`] = 126 | KVec[`tId`](inner: `getFunc`[`kType`](t.inner.k.dict.values, `iId`)) 127 | 128 | var params = newSeq[NimNode]() 129 | params.add newBracketExpr(ident "seq", kType) 130 | params.add newIdentDefs(ident "t", newBracketExpr(ident "KTable", typeDefId)) 131 | params.add newIdentDefs(ident "x", typeDefId) 132 | 133 | var body = newStmtList() 134 | for i, (x, _) in fields: 135 | let val = ident("v" & $i) 136 | body.add newLetStmt(val, newCall(newDotExpr(newDotExpr(ident"x", ident x), toKFunc))) 137 | body.add newDiscardStmt(newCall(r1Func, newDotExpr(val, ident"k"))) 138 | body.add newCommand(newDotExpr(ident"result", ident"add"), val) 139 | 140 | let g = newProc(ident("genValues"), params, body) 141 | result.add g 142 | 143 | result.add quote do: 144 | proc checkDefinition(_: `typeDefId`) = 145 | discard 146 | 147 | macro fields(t: typed): untyped = 148 | let fields = getFieldsRec(getType(t)[1]) 149 | var fieldsTyped: seq[(string, KKind)] = @[] 150 | for (f, t) in fields: 151 | fieldsTyped.add((f, stringToKVecKind(t))) 152 | 153 | result = quote do: 154 | @`fieldsTyped` 155 | 156 | proc newKTable*(T: typedesc): KTable[T] = 157 | when not compiles(checkDefinition(T())): 158 | {.fatal: "defineTable".} 159 | let fields = fields(T) 160 | # echo "newKTable: ", fields 161 | let kTable = newKTable(fields) 162 | KTable[T](inner: kTable, moved: false) 163 | 164 | proc checkK[T](k: K) = 165 | let fields = fields(T) 166 | for k, v in k.pairs(): 167 | var found = false 168 | for kk in fields: 169 | if kk[0] == $k: 170 | if kk[1] != v.kind: 171 | raise newException(Exception, "check failed: fields `" & $k & "` expected " & $kk[1] & " but received " & $v.kind) 172 | found = true 173 | break 174 | 175 | if not found: 176 | raise newException(Exception, "check failed: fields `" & $k & "` is not found in schema definition") 177 | 178 | proc toKTable*(k: K, T: typedesc, check = false): KTable[T] = 179 | when not compiles(checkDefinition(T())): 180 | {.fatal: "defineTable".} 181 | checkK[T](k) 182 | KTable[T](inner: k, moved: false) 183 | 184 | template add*[T](t: var KTable[T], x: T) = 185 | checkMoved(t) 186 | let vals = t.genValues(x) 187 | # t.inner.addRow(vals) 188 | addRow(t.inner, vals) 189 | 190 | proc newTypedColumn(k: KKind, size: int): K = 191 | case k 192 | of KKind.kVecFloat: %newSeq[float](size) 193 | of KKind.kVecLong: %newSeq[int](size) 194 | else: raise newException(KError, "newKVecTyped: " & $k) 195 | 196 | macro transformCheck(t: typed, tt: typed, j: varargs[typed]): untyped = 197 | if getType(t) == getType(tt): 198 | warning("transform into itself") 199 | 200 | let fieldsFrom = getFieldsRec(getType(t)[1]) 201 | let fieldsTo = getFieldsRec(getType(tt)[1]) 202 | # echo "fieldsCheck: " 203 | # echo " from: ", fieldsFrom 204 | # echo " to: ", fieldsTo 205 | 206 | let toAdd = calcToAdd(fieldsFrom, fieldsTo) 207 | let toDel = calcToDelete(fieldsFrom, fieldsTo) 208 | 209 | if j.len > 0: 210 | var i = 0 211 | for x in toAdd: 212 | let jType = getType(j[0])[1].strVal 213 | # echo " j: ", jType 214 | # echo x[1], " - ", jType 215 | if x[1] != jType: 216 | if not (x[1] == "Sym" and jType == "string"): 217 | error("transform error: expected: " & x[1] & ", provided: " & jType) 218 | inc(i) 219 | if i < j.len: 220 | error("transform error: too many columns provided") 221 | 222 | var toAddKind: seq[(string, KKind)] = @[] 223 | for (f, t) in toAdd: 224 | toAddKind.add((f, stringToKVecKind(t))) 225 | 226 | result = quote do: 227 | checkMoved(t) 228 | (@`toAddKind`, @`toDel`) 229 | 230 | proc transform*[T](t: var KTable[T], TT: typedesc): KTable[TT] = 231 | let toChange = transformCheck(T, TT) 232 | 233 | for (x, k) in toChange[0]: 234 | t.inner.addColumnWithKind(x, k, newTypedColumn(k, t.inner.len)) 235 | 236 | for x in toChange[1]: 237 | t.inner.deleteColumn(x) 238 | 239 | t.moved = true 240 | result = KTable[TT](inner: t.inner, moved: false) 241 | 242 | proc toKOrSym[T](k: KKind, x: openArray[T]): K = 243 | when T is string: 244 | if k == KKind.kVecSym: 245 | toK(x.mapIt(newSym(it))) 246 | else: 247 | toK(x) 248 | else: 249 | toK(x) 250 | 251 | proc transform*[T, J](t: KTable[T], TT: typedesc, col1: openArray[J]): KTable[TT] = 252 | let toChange = transformCheck(T, TT, J) 253 | 254 | let addCol1 = toChange[0][0] 255 | t.inner.addColumnWithKind(addCol1[0], addCol1[1], toKOrSym(addCol1[1], col1)) 256 | 257 | for x in toChange[1]: 258 | t.inner.deleteColumn(x) 259 | 260 | t.moved = true 261 | KTable[TT](inner: t.inner, moved: false) 262 | 263 | proc transform*[T, J, JJ](t: KTable[T], TT: typedesc, col1: openArray[J], col2: openArray[JJ]): KTable[TT] = # TODO: template? macros? 264 | let toChange = transformCheck(T, TT, J, JJ) 265 | 266 | let addCol1 = toChange[0][0] 267 | t.inner.addColumnWithKind(addCol1[0], addCol1[1], toKOrSym(addCol1[1], col1)) 268 | let addCol2 = toChange[0][1] 269 | t.inner.addColumnWithKind(addCol2[0], addCol2[1], toKOrSym(addCol2[1], col2)) 270 | 271 | for x in toChange[1]: 272 | kk.deleteColumn(x) 273 | 274 | t.moved = true 275 | KTable[TT](inner: t.inner, moved: false) 276 | 277 | proc transform*[T, J, JJ, JJJ](t: KTable[T], TT: typedesc, col1: openArray[J], col2: openArray[JJ], col3: openArray[JJJ]): KTable[TT] = 278 | let toChange = transformCheck(T, TT, J, JJ, JJJ) 279 | 280 | let addCol1 = toChange[0][0] 281 | t.inner.addColumnWithKind(addCol1[0], addCol1[1], toKOrSym(addCol1[1], col1)) 282 | let addCol2 = toChange[0][1] 283 | t.inner.addColumnWithKind(addCol2[0], addCol2[1], toKOrSym(addCol2[1], col3)) 284 | let addCol3 = toChange[0][2] 285 | t.inner.addColumnWithKind(addCol3[0], addCol3[1], toKOrSym(addCol3[1], col3)) 286 | 287 | for x in toChange[1]: 288 | kk.deleteColumn(x) 289 | 290 | t.moved = true 291 | KTable[TT](inner: t.inner, moved: false) 292 | 293 | proc toK*(t: KTable):K = 294 | t.inner 295 | 296 | # dumpTree: 297 | # proc genValues(t: KTable[T1], x: T1): seq[K] = 298 | # let v1 = x.price.toK() 299 | # discard r1(v1.k) 300 | # result.add(v1) 301 | # let v2 = x.name.toK() 302 | # discard r1(v2.k) 303 | # result.add(v2) 304 | -------------------------------------------------------------------------------- /src/kdb/high/vec.nim: -------------------------------------------------------------------------------- 1 | import kdb/low 2 | 3 | type 4 | KVec*[T] = object 5 | inner*: K 6 | 7 | proc newKVec*[T](): KVec[T] = 8 | let kVec = low.newKVec[T]() 9 | KVec[T](inner: kVec) 10 | 11 | # proc newKVecTyped(k: KKind, size: int): KVec 12 | 13 | proc add*[T](v: var KVec[T], x: T) = 14 | v.inner.add(%x) # TODO: not ok for not list 15 | 16 | proc `$`*(v: KVec): string = 17 | $v.inner 18 | 19 | proc len*(v: KVec): int = 20 | v.inner.len() 21 | 22 | proc `[]`*[U](v: KVec[seq[seq[U]]], idx: int): KVec[seq[U]] = 23 | KVec[seq[U]](inner: v.inner.get[:K](idx)) 24 | 25 | proc `[]`*[U](v: KVec[seq[U]], idx: int): KVec[U] = 26 | KVec[U](inner: v.inner.get[:K](idx)) 27 | 28 | proc `[]`*[T](v: KVec[T], idx: int): T = 29 | v.inner.get[:T](idx) 30 | 31 | iterator items*[T](v: KVec[T]): T = 32 | for x in v.inner.items(T): 33 | yield x 34 | 35 | iterator mitems*[T](v: var KVec[T]): var T = 36 | for i in 0.. format + procs -> converters -> bindings -> types 6 | 7 | initMemory() 8 | -------------------------------------------------------------------------------- /src/kdb/low/access.nim: -------------------------------------------------------------------------------- 1 | import converters 2 | export converters 3 | 4 | import uuids 5 | import endians 6 | import times 7 | 8 | # Imported to compare two vecChars effective 9 | proc c_memcmp*(a, b: pointer, size: csize_t): cint {. 10 | importc: "memcmp", header: "", noSideEffect.} 11 | 12 | proc getBool*(x: K): bool = 13 | assert x.k.kind == KKind.kBool 14 | x.k.bb 15 | 16 | proc getGUID*(x: K): UUID = 17 | var twoInts64 = cast[ptr UncheckedArray[int64]](x.k.gg.g.addr) 18 | var most: int64 19 | var least: int64 20 | bigEndian64(most.addr, twoInts64[0].addr) 21 | bigEndian64(least.addr, twoInts64[1].addr) 22 | initUUID(most, least) 23 | 24 | proc getByte*(x: K): byte = 25 | assert x.k.kind == KKind.kByte 26 | x.k.by 27 | 28 | proc getInt16*(x: K): int16 = 29 | assert x.k.kind == KKind.kShort 30 | x.k.sh 31 | 32 | proc getInt32*(x: K): int64 = 33 | assert x.k.kind == KKind.kInt 34 | x.k.ii 35 | 36 | proc getInt64*(x: K): int64 = 37 | assert x.k.kind == KKind.kLong 38 | x.k.jj 39 | 40 | proc getInt*(x: K): int = 41 | assert x.k.kind == KKind.kLong 42 | x.k.jj.int 43 | 44 | proc getFloat32*(x: K): float32 = 45 | assert x.k.kind == KKind.kReal 46 | x.k.rr 47 | 48 | proc getFloat64*(x: K): float64 = 49 | assert x.k.kind == KKind.kFloat 50 | x.k.ff 51 | 52 | proc getFloat*(x: K): float = 53 | assert x.k.kind == KKind.kFloat 54 | x.k.ff 55 | 56 | proc getChar*(x: K): char = 57 | assert x.k.kind == KKind.kChar 58 | x.k.ch 59 | 60 | proc getStr*(x: K): string = 61 | case x.k.kind 62 | of KKind.kSym: result = $x.k.ss 63 | of KKind.kVecChar: 64 | result = newString(x.k.charLen) 65 | if result.len > 0: 66 | copyMem(result[0].addr, x.k.charArr.addr, x.k.charLen) 67 | else: 68 | raise newException(KError, "getStr() is not available for " & $x.k.kind) 69 | 70 | proc getDateTime*(x: K): DateTime = 71 | assert x.k.kind == KKind.kDateTime 72 | let d = initDuration(milliseconds = int64(86400000*x.k.dt)) 73 | let dt = initDateTime(1, mJan, 2000, 0, 0, 0, utc()) + d 74 | dt 75 | 76 | proc getTime*(x: K): Time = 77 | let seconds = (x.k.ts div 1000000000) + 10957*86400 78 | let nanos = x.k.ts mod 1000000000 79 | let t = initTime(seconds, nanos) 80 | t 81 | 82 | template math1(op: untyped) = 83 | proc op*(a: K): K = 84 | case a.k.kind 85 | # of kByte: op(a.k.by) # TODO: WHY ? 86 | of kShort: toK(op(a.k.sh)) 87 | of kInt: toK(op(a.k.ii)) 88 | of kLong: toK(op(a.k.jj)) 89 | of kReal: toK(op(a.k.rr)) # TODO: WHY ? 90 | of kFloat: toK(op(a.k.ff)) 91 | else: raise newException(KError, "OP is not supported for " & $a.k.kind) 92 | 93 | template math2(op: untyped) = 94 | proc op*(a, b: K): K = 95 | assert a.k.kind == b.k.kind 96 | case a.k.kind 97 | of kByte: toK(op(a.k.by, b.k.by)) 98 | of kShort: toK(op(a.k.sh, b.k.sh)) 99 | of kInt: toK(op(a.k.ii, b.k.ii)) 100 | of kLong: toK(op(a.k.jj, b.k.jj)) 101 | of kReal: toK(op(a.k.rr, b.k.rr)) # TODO: WHY ? 102 | of kFloat: toK(op(a.k.ff, b.k.ff)) 103 | else: raise newException(KError, "OP is not supported for " & $a.k.kind) 104 | 105 | template math2Int(op: untyped) = 106 | proc op*(a, b: K): K = 107 | assert a.k.kind == b.k.kind 108 | case a.k.kind 109 | of kByte: toK(op(a.k.by, b.k.by)) 110 | of kShort: toK(op(a.k.sh, b.k.sh)) 111 | of kInt: toK(op(a.k.ii, b.k.ii)) 112 | of kLong: toK(op(a.k.jj, b.k.jj)) 113 | else: raise newException(KError, "OP is not supported for " & $a.k.kind) 114 | 115 | template math2var(op: untyped) = 116 | proc op*(a: var K, b: K) = 117 | assert a.k.kind == b.k.kind 118 | case a.k.kind 119 | of kByte: op(a.k.by, b.k.by) 120 | of kShort: op(a.k.sh, b.k.sh) 121 | of kInt: op(a.k.ii, b.k.ii) 122 | of kLong: op(a.k.jj, b.k.jj) 123 | of kReal: op(a.k.rr, b.k.rr) 124 | of kFloat: op(a.k.ff, b.k.ff) 125 | else: raise newException(KError, "OP is not supported for " & $a.k.kind) 126 | 127 | template mathCmp(op: untyped) = 128 | proc op*(a, b: K): bool = 129 | assert a.k.kind == b.k.kind 130 | case a.k.kind 131 | of kByte: op(a.k.by, b.k.by) 132 | of kShort: op(a.k.sh, b.k.sh) 133 | of kInt: op(a.k.ii, b.k.ii) 134 | of kLong: op(a.k.jj, b.k.jj) 135 | of kReal: op(a.k.rr, b.k.rr) 136 | of kFloat: op(a.k.ff, b.k.ff) 137 | else: raise newException(KError, "OP is not supported for " & $a.k.kind) 138 | 139 | math1(`-`) 140 | math2(`+`) 141 | math2(`-`) 142 | math2(`*`) 143 | math2Int(`div`) 144 | math2Int(`mod`) 145 | mathCmp(`<`) 146 | mathCmp(`<=`) 147 | math2var(`+=`) 148 | math2var(`-=`) 149 | math2var(`*=`) 150 | 151 | proc `==`*(a: K0, b: K0): bool = 152 | if isNil(a) and isNil(b): 153 | return true 154 | if isNil(a) or isNil(b): # xor 155 | return false 156 | if a.kind != b.kind: 157 | return false 158 | case a.kind 159 | of kBool: a.bb == b.bb 160 | of kGUID: a.gg.g == b.gg.g 161 | of kByte: a.by == b.by 162 | of kShort: a.sh == b.sh 163 | of kInt: a.ii == b.ii 164 | of kLong: a.jj == b.jj 165 | of kReal: a.rr == b.rr 166 | of kFloat: a.ff == b.ff 167 | of kChar: a.ch == b.ch 168 | of kSym: a.ss == b.ss 169 | of kTimestamp: a.ts == b.ts 170 | of kDateTime: a.dt == b.dt 171 | of kVecChar: 172 | if a.charLen == b.charLen: 173 | 0 == c_memcmp(a.charArr.addr, b.charArr.addr, a.charLen.csize_t) 174 | else: 175 | false 176 | of kVecLong: 177 | var vA: seq[int64] 178 | vA.add toOpenArray(a.longArr.addr, 0, a.longLen.int - 1) 179 | var vB: seq[int64] 180 | vB.add toOpenArray(b.longArr.addr, 0, b.longLen.int - 1) 181 | vA == vB 182 | of kVecFloat: 183 | var vA: seq[float] 184 | vA.add toOpenArray(a.floatArr.addr, 0, a.floatLen.int - 1) 185 | var vB: seq[float] 186 | vB.add toOpenArray(b.floatArr.addr, 0, b.floatLen.int - 1) 187 | vA == vB 188 | of kVecSym: # TODO: maybe slow: check 189 | var vA: seq[cstring] 190 | vA.add toOpenArray(a.stringArr.addr, 0, a.stringLen.int - 1) 191 | var vB: seq[cstring] 192 | vB.add toOpenArray(b.stringArr.addr, 0, b.stringLen.int - 1) 193 | vA == vB 194 | of kList: # TODO: probably too slow: remake 195 | var vA: seq[K0] 196 | vA.add toOpenArray(a.kArr.addr, 0, a.kLen.int - 1) 197 | var vB: seq[K0] 198 | vB.add toOpenArray(b.kArr.addr, 0, b.kLen.int - 1) 199 | vA == vB 200 | else: raise newException(KError, "`==` is not supported for " & $a.kind) 201 | 202 | proc `==`*(a, b: K): bool = 203 | a.k == b.k 204 | 205 | -------------------------------------------------------------------------------- /src/kdb/low/bindings.nim: -------------------------------------------------------------------------------- 1 | import types 2 | export types 3 | 4 | 5 | when defined(windows): 6 | from winlean import SocketHandle 7 | export winlean.SocketHandle 8 | else: 9 | from posix import SocketHandle 10 | export posix.SocketHandle 11 | 12 | proc kb*(x: bool): K0 {. 13 | importc: "kb", header: "k.h".} 14 | 15 | proc ks*(x: cstring): K0 {. 16 | importc: "ks", header: "k.h".} 17 | 18 | proc kp*(x: cstring): K0 {. 19 | importc: "kp", header: "k.h".} 20 | 21 | proc kpn*(x: cstring, n: clonglong): K0 {. 22 | importc: "kpn", header: "k.h".} 23 | 24 | proc ku*(x: GUID): K0 {. 25 | importc: "ku", header: "k.h".} 26 | 27 | proc kh*(x: cint): K0 {. 28 | importc: "kh", header: "k.h".} 29 | 30 | proc kg*(x: cint): K0 {. 31 | importc: "kg", header: "k.h".} 32 | 33 | proc ki*(x: cint): K0 {. 34 | importc: "ki", header: "k.h".} 35 | 36 | proc kj*(x: clonglong): K0 {. 37 | importc: "kj", header: "k.h".} 38 | 39 | proc ke*(x: cfloat): K0 {. 40 | importc: "ke", header: "k.h".} 41 | 42 | proc kf*(x: cdouble): K0 {. 43 | importc: "kf", header: "k.h".} 44 | 45 | proc kc*(x: cchar): K0 {. 46 | importc: "kc", header: "k.h".} 47 | 48 | proc ka*(x: byte): K0 {. 49 | importc: "ka", header: "k.h".} 50 | 51 | proc km*(x: cint): K0 {. 52 | importc: "km".} 53 | 54 | proc kmi*(x: cint): K0 {. 55 | importc: "kmi".} 56 | 57 | proc kse*(x: cint): K0 {. 58 | importc: "kse".} 59 | 60 | proc kd*(x: cint): K0 {. 61 | importc: "kd", header: "k.h".} 62 | 63 | proc kz*(x: cdouble): K0 {. 64 | importc: "kz", header: "k.h".} 65 | 66 | proc ktj*(t: byte, x: clonglong): K0 {. 67 | importc: "ktj", header: "k.h".} 68 | 69 | proc kt*(x: cint): K0 {. 70 | importc: "kt", header: "k.h".} 71 | 72 | proc knk*(i: int): K0 {. 73 | importc: "knk", header: "k.h".} 74 | 75 | proc jk*(l: ptr K0, x: K0) {. 76 | importc: "jk", header: "k.h".} 77 | 78 | proc jv*(l: ptr K0, x: K0) {. 79 | importc: "jv", header: "k.h".} 80 | 81 | proc ktn*(t:int, i: int): K0 {. 82 | importc: "ktn", header: "k.h".} 83 | 84 | proc js*(l: ptr K0, x: cstring) {. 85 | importc: "js", header: "k.h".} 86 | 87 | proc ja*(l: ptr K0, x: ptr SomeNumber) {. 88 | importc: "ja", header: "k.h".} 89 | 90 | proc ja*(l: ptr K0, x: ptr bool) {. 91 | importc: "ja", header: "k.h".} 92 | 93 | proc ja*(l: ptr K0, x: ptr GUID) {. 94 | importc: "ja", header: "k.h".} 95 | 96 | proc ss*(x: cstring): cstring {. 97 | importc: "ss", header: "k.h".} 98 | 99 | proc xD*(k: K0, v: K0): K0 {. 100 | importc: "xD", header: "k.h".} 101 | 102 | proc xT*(x: K0): K0 {. 103 | importc: "xT", header: "k.h".} 104 | 105 | proc kK*(x: K0): K0 {. 106 | importc: "kK", header: "k.h".} 107 | 108 | proc khp*(x: cstring, p: int): SocketHandle {. 109 | importc: "khp", header: "k.h".} 110 | 111 | proc k*(h: SocketHandle, a: typeof(nil)): K0 {. 112 | importc: "k", header: "k.h".} 113 | 114 | proc k*(h: SocketHandle, x: cstring, a: K0): K0 {. 115 | importc: "k", header: "k.h".} 116 | 117 | proc k*(h: SocketHandle, x: cstring, a, b: K0): K0 {. 118 | importc: "k", header: "k.h".} 119 | 120 | proc k*(h: SocketHandle, x: cstring, a, b, c: K0): K0 {. 121 | importc: "k", header: "k.h".} 122 | 123 | proc k*(h: SocketHandle, x: cstring, a, b, c, d: K0): K0 {. 124 | importc: "k", header: "k.h".} 125 | 126 | proc k*(h: SocketHandle, v: K0, n: typeof(nil)): K0 {. 127 | importc: "k", header: "k.h".} 128 | 129 | proc kerr*(x: cstring): K0 {. 130 | importc: "kerr".} 131 | 132 | proc b9*(t: cint, v: K0): K0 {. 133 | importc: "b9", header: "k.h".} 134 | 135 | proc d9*(x: K0): K0 {. 136 | importc: "d9", header: "k.h".} 137 | 138 | proc checkCStructOffset*() {. 139 | importc: "check_c_struct_offset".} 140 | 141 | proc checkNimStructOffset*() = 142 | echo "Nim-struct-offset:" 143 | echo " m: ", offsetof(K0, m) 144 | echo " a: ", offsetof(K0, a) 145 | echo " t: ", offsetof(K0, kind) 146 | echo " u: ", offsetof(K0, tu) 147 | echo " r: ", offsetof(K0, tr) 148 | echo " k: ", offsetof(K0, dict) 149 | echo " n: ", offsetof(K0, kLen) 150 | echo " g0: ", offsetof(K0, kArr) 151 | 152 | 153 | -------------------------------------------------------------------------------- /src/kdb/low/converters.nim: -------------------------------------------------------------------------------- 1 | import bindings 2 | export bindings 3 | 4 | import uuids 5 | import endians 6 | import times 7 | 8 | type 9 | Sym* = object # it is for high module, but it is here to support toK 10 | inner*: K 11 | 12 | proc typeToKKind*[T](): KKind = 13 | when T is bool: KKind.kBool 14 | elif T is GUID: KKind.kGUID 15 | elif T is byte: KKind.kByte 16 | elif T is int16: KKind.kShort 17 | elif T is int32: KKind.kInt 18 | elif T is int: KKind.kLong 19 | elif T is int64: KKind.kLong 20 | elif T is float32: KKind.kReal 21 | elif T is float64: KKind.kFloat 22 | elif T is float: KKind.kFloat 23 | elif T is KSym: KKind.kSym 24 | elif T is Sym: KKind.kSym 25 | elif T is KTimestamp: KKind.kTimestamp 26 | elif T is KDateTime: KKind.kDateTime 27 | elif T is DateTime: KKind.kDateTime 28 | elif T is KList: KKind.kList 29 | elif T is string: KKind.kList 30 | elif T is typeof(nil): KKind.kList 31 | else: KKind.kList # raise newException(KError, "cannot convert type " & $T) 32 | 33 | proc toVecKKind*(k: KKind): KKind = 34 | case k: 35 | of KKind.kBool: KKind.kVecBool 36 | of KKind.kGUID: KKind.kVecGUID 37 | of KKind.kByte: KKind.kVecByte 38 | of KKind.kShort: KKind.kVecShort 39 | of KKind.kInt: KKind.kVecInt 40 | of KKind.kLong: KKind.kVecLong 41 | of KKind.kReal: KKind.kVecReal 42 | of KKind.kFloat: KKind.kVecFloat 43 | of KKind.kSym: KKind.kVecSym 44 | of KKind.kTimestamp: KKind.kVecTimestamp 45 | of KKind.kDateTime: KKind.kVecDateTime 46 | else: KKind.kList 47 | 48 | proc toK*(x: Sym): K = 49 | x.inner 50 | 51 | proc toK*(x: type(nil)): K = 52 | result = K(k: ka(101)) 53 | result.k.idg = 0 54 | 55 | proc toK*(x: cstring): K = 56 | K(k: kpn(x, x.len)) 57 | 58 | proc toK*(x: string): K = 59 | K(k: kpn(x.cstring, x.len)) 60 | 61 | proc toK*(x: int16): K= 62 | K(k: kh(x)) 63 | 64 | proc toK*(x: int32): K= 65 | K(k: ki(x)) 66 | 67 | proc toK*(x: int): K = 68 | K(k: kj(x)) 69 | 70 | proc toK*(x: int64): K = 71 | K(k: kj(x)) 72 | 73 | proc toK*(x: float32): K = 74 | K(k: ke(x)) 75 | 76 | proc toK*(x: float64): K = 77 | K(k: kf(x)) 78 | 79 | proc toK*(x: char): K = 80 | K(k: kc(x)) 81 | 82 | proc toSym*(x: cstring): K = 83 | K(k: ks(x)) 84 | 85 | proc toSym*(x: string): K = 86 | toSym(x.cstring) 87 | 88 | proc `s`*(x: string): K = 89 | K(k: ks(x.cstring)) 90 | 91 | proc toKError*(x: string): K = 92 | let k0 = kerr(x.cstring) 93 | K(k: k0) 94 | 95 | proc toKMonth*(x: int32): K = 96 | K(k: km(x)) 97 | 98 | proc toKMinute*(x: int32): K = 99 | K(k: kmi(x)) 100 | 101 | proc toKSecond*(x: int32): K = 102 | K(k: kse(x)) 103 | 104 | proc toKDate*(x: int32): K = 105 | K(k: kd(x)) 106 | 107 | proc toKDateTime*(x: float64): K = 108 | K(k: kz(x)) 109 | 110 | proc toKTimestamp*(x: int64): K = 111 | K(k: ktj(KKind.kTimestamp.byte, x)) 112 | 113 | proc toKTimespan*(x: int64): K = 114 | K(k: ktj(KKind.kTimespan.byte, x)) 115 | 116 | proc toKTime*(x: int32): K = 117 | K(k: kt(x)) 118 | 119 | proc toK*(x: byte): K = 120 | K(k: kg(x.int32)) 121 | 122 | proc toK*(x: bool): K = 123 | K(k: kb(x)) 124 | 125 | proc toK*(x: GUID): K = 126 | K(k: ku(x)) 127 | 128 | proc toK*(uuid: UUID): K = 129 | let src1 = uuid.mostSigBits 130 | let src2 = uuid.leastSigBits 131 | var dst1: int64 132 | var dst2: int64 133 | bigEndian64(dst1.addr, src1.unsafeAddr) 134 | bigEndian64(dst2.addr, src2.unsafeAddr) 135 | 136 | let guid = cast[GUID]((dst1, dst2)) 137 | K(k: ku(guid)) 138 | 139 | proc toGUID*(x: string): K = 140 | let uuid = parseUUID(x) 141 | toK(uuid) 142 | 143 | proc toK*(x: array[16, byte]): K = 144 | let guid = GUID(g: x) 145 | toK(guid) 146 | 147 | proc toNanos*(x: Time): int64 = 148 | let seconds = x.toUnix() - 10957*86400 149 | seconds*1000000000 + x.nanosecond() 150 | 151 | proc toMillis*(x: DateTime): float64 = 152 | let d = x - initDateTime(1, mJan, 2000, 0, 0, 0, utc()) 153 | d.inMilliseconds().float64 / 86400000 154 | 155 | proc toKTimestamp*(x: Time): K = 156 | toKTimestamp(x.toNanos()) 157 | 158 | proc toK*(x: Time): K = 159 | toKTimestamp(x) 160 | 161 | proc toK*(x: DateTime): K = 162 | toKDateTime(x.toMillis()) 163 | 164 | proc toSymVec*(columns: openArray[string]): K = 165 | let k0 = ktn(typeToKKind[KSym]().toVecKKind().int, columns.len) 166 | for i, x in columns: 167 | k0.stringArr[i] = ss(x.cstring) 168 | result = K(k: k0) 169 | 170 | proc toK*[T](v: openArray[seq[T]]): K = 171 | result = K(k: ktn(KKind.kList.int, v.len)) 172 | # TODO: unimplemented 173 | 174 | proc toK*[T](v: openArray[T]): K = 175 | when T is DateTime: 176 | result = K(k: ktn(typeToKKind[T]().toVecKKind().int, v.len)) 177 | for i, x in v: 178 | result.k.dtArr[i] = x.toMillis() 179 | elif T is SomeNumber: 180 | result = K(k: ktn(typeToKKind[T]().toVecKKind().int, v.len)) 181 | case result.k.kind 182 | of kVecLong: 183 | for i, x in v: 184 | result.k.longArr[i] = x.int64 185 | of kVecFloat: 186 | for i, x in v: 187 | result.k.floatArr[i] = x.float64 188 | else: raise newException(KError, "openArray proc is not supported for " & $result.k.kind) 189 | elif T is string: 190 | result = K(k: ktn(typeToKKind[T]().int, v.len)) 191 | for i, x in v: 192 | let k = x.toK() 193 | result.k.kArr[i] = r1(k.k) 194 | elif T is Sym: 195 | result = K(k: ktn(typeToKKind[T]().toVecKKind().int, v.len)) 196 | discard r1(result.k) 197 | for i, x in v: 198 | result.k.stringArr[i] = x.inner.k.ss 199 | elif T is K: 200 | result = K(k: ktn(typeToKKind[nil]().int, v.len)) 201 | for i, x in v: 202 | result.k.kArr[i] = r1(x.k) 203 | else: 204 | raise newException(KError, "openArray proc is not supported for " & $T) 205 | 206 | proc toK*(x: K0): K = 207 | K(k: r1(x)) 208 | 209 | proc toK*(x: K): K = # for varargs[K] support 210 | x 211 | 212 | template `%`*(x: typed): K = 213 | toK(x) 214 | 215 | # proc fromK(x: K): int = 216 | # assert x.k.kind == KKind.kLong 217 | # x.k.jj.int 218 | 219 | -------------------------------------------------------------------------------- /src/kdb/low/format.nim: -------------------------------------------------------------------------------- 1 | #import procs 2 | #export procs 3 | import access 4 | export access 5 | 6 | import strutils 7 | import times 8 | import terminaltables 9 | import uuids 10 | 11 | const monthFormat = initTimeFormat("yyyy-MM") 12 | const dateFormat = initTimeFormat("yyyy-MM-dd") 13 | const dateTimeFormat = initTimeFormat("yyyy-MM-dd\'T\'HH:mm:ss\'.\'fff") 14 | const timestampFormat = "yyyy-MM-dd\'T\'HH:mm:ss\'.\'fffffffff" 15 | const timespanFormat = "HH:mm:ss\'.\'fffffffff" 16 | const minuteFormat = "HH:mm" 17 | const secondFormat = "HH:mm:ss" 18 | const timeFormat = "HH:mm:ss\'.\'fff" 19 | 20 | proc `$`*(x: K): string {.gcsafe.} 21 | 22 | include procs 23 | 24 | proc fmtKList(x: K): string = 25 | result.add "(" 26 | for i in 0.. 0: 28 | result.add "; " 29 | result.add $toK(x.k.kArr[i]) 30 | result.add ")" 31 | 32 | proc flatoKTable*(x: K): string = 33 | result.add "|" 34 | for i in 0.. 0: 36 | result.add ", " 37 | result.add $x.k.dict.keys[i] & ": " 38 | result.add $x.k.dict.values[i] 39 | result.add "|" 40 | 41 | proc fmtKTable(x: K): string {.gcsafe.} = 42 | let t = newUnicodeTable() 43 | t.separateRows = false 44 | var header: seq[string] = @[] 45 | for x in toK(x.k.dict.keys): # TODO: strange r1 46 | header.add $x # to remove quoted names 47 | t.setHeaders(header) 48 | 49 | for i in 0.. 0: 62 | result.add "; " 63 | result.add $x.k.keys[i] & ": " & $x.k.values[i] 64 | result.add "}" 65 | 66 | proc fmtKVec(x: K): string = 67 | result.add "[" 68 | for i in 0.. 0: 70 | result.add ", " 71 | result.add $x.k[i] 72 | result.add "]" 73 | 74 | proc fmtKGUID(x: K): string = 75 | $x.getGUID() 76 | 77 | proc `$`*(x: K): string {.gcsafe.} = 78 | if isNil(x.k): 79 | return "nil" 80 | case x.k.kind 81 | of kList: 82 | result.add fmtKList(x) 83 | of kTable: 84 | result.add fmtKTable(x) 85 | of kDict: 86 | result.add fmtKDict(x) 87 | of kGUID: 88 | result.add fmtKGUID(x) 89 | of kByte: 90 | result.add $x.k.by.int # TODO: cannot convert via byte: fix 91 | of kShort: 92 | result.add $x.k.sh 93 | of kInt: 94 | result.add $x.k.ii 95 | of kLong: 96 | result.add if x.k.jj == 0x8000000000000000: "NaN" else: $x.k.jj 97 | of kReal: 98 | result.add $x.k.rr 99 | of kFloat: 100 | result.add $x.k.ff 101 | of kChar: 102 | result.add "'" & $x.k.ch & "'" 103 | of kSym: 104 | result.add getStr(x) 105 | of kBool: 106 | result.add $x.k.bb.bool 107 | of kId: 108 | result.add "(::)" 109 | of kError: 110 | result.add $x.k.msg 111 | of kTimestamp: 112 | result.add x.getTime().utc().format(timestampFormat) 113 | of kMonth: 114 | let d = initTimeInterval(months = x.k.mo) 115 | let dt = initDateTime(1, mJan, 2000, 0, 0, 0, utc()) + d 116 | result.add dt.format(monthFormat) 117 | of kDate: 118 | let d = initDuration(days = x.k.dd) 119 | let dt = initDateTime(1, mJan, 2000, 0, 0, 0, utc()) + d 120 | result.add dt.format(dateFormat) 121 | of kDateTime: 122 | result.add $x.getDateTime() 123 | of kTimespan: 124 | let d = initTime(0, 0) + initDuration(nanoseconds = x.k.tp) 125 | let days = int(d.toUnixFloat() / (24*3600)) 126 | result.add $days & "D" & d.format(timespanFormat, zone = utc()) 127 | of kMinute: 128 | let d = initTime(0, 0) + initDuration(minutes = x.k.mi) 129 | result.add d.format(minuteFormat, zone = utc()) 130 | of kSecond: 131 | let d = initTime(0, 0) + initDuration(seconds = x.k.se) 132 | result.add d.format(secondFormat, zone = utc()) 133 | of kTime: 134 | let d = initTime(0, 0) + initDuration(milliseconds = x.k.tt) 135 | result.add d.format(timeFormat, zone = utc()) 136 | of kVecChar: 137 | result.add '"' & x.getStr() & '"' 138 | of kVecInt, kVecSym, kVecBool, kVecByte, kVecShort, 139 | kVecLong, kVecReal, kVecFloat, 140 | kVecMonth, kVecMinute, kVecSecond, 141 | kVecDateTime, kVecTimestamp, kVecTimespan: 142 | result.add fmtKVec(x) 143 | of kVecGUID: 144 | result.add fmtKVec(x) 145 | else: 146 | result.add $x.k.kind & ": unknown" 147 | -------------------------------------------------------------------------------- /src/kdb/low/ipc.nim: -------------------------------------------------------------------------------- 1 | import format 2 | export format 3 | 4 | import net 5 | import endians 6 | 7 | proc connect*(hostname: string, port: int): SocketHandle = 8 | result = khp(hostname, port) 9 | if result.int <= 0: 10 | raise newException(KError, "Connection error") 11 | 12 | proc execIntenal(h: SocketHandle, s: string, args: varargs[K]): K0 = 13 | case args.len 14 | of 0: result = k(h, s.cstring, nil) 15 | of 1: result = k(h, s.cstring, args[0].k, nil) 16 | of 2: result = k(h, s.cstring, args[0].k, args[1].k, nil) 17 | of 3: result = k(h, s.cstring, args[0].k, args[1].k, args[2].k, nil) 18 | else: raise newException(KError, "Cannot exec with more than 3 arguments") 19 | 20 | if result.kind == KKind.kError: 21 | raise newException(KErrorRemote, $result.msg) 22 | 23 | proc exec*(h: SocketHandle, s: string, args: varargs[K]): K = 24 | let k0 = execIntenal(h, s, args) 25 | 26 | if k0.kind == KKind.kError: 27 | var str = newString(result.k.charLen) 28 | copyMem(str[0].addr, result.k.charArr.addr, result.k.charLen) 29 | r0(k0) 30 | 31 | raise newException(KErrorRemote, str) 32 | else: 33 | K(k: k0) 34 | 35 | # proc exec0*(h: SocketHandle, s: string): K = 36 | # exec(h, s, nil.toK()) 37 | 38 | proc execAsync*(h: SocketHandle, s: string, args: varargs[K]) = 39 | let negSocket = (-(h.int)).SocketHandle 40 | discard execIntenal(negSocket, s, args) 41 | 42 | # proc execAsync0*(h: SocketHandle, s: string) = 43 | # execAsync(h, s, nil.toK()) 44 | 45 | proc read*(h: SocketHandle): K = 46 | let k0 = k(h, nil) 47 | K(k: k0) 48 | 49 | proc sendAsync*(h: SocketHandle, v: K) = 50 | let socket = newSocket(h) 51 | 52 | let data = b9(3, v.k) 53 | data.byteArr[1] = 0 # async type 54 | let sent = socket.send(data.byteArr.addr, data.byteLen.int) 55 | assert sent == data.byteLen 56 | r0(data) 57 | 58 | proc sendSyncReply*(h: SocketHandle, v: K) = 59 | let socket = newSocket(h) 60 | 61 | case v.kind 62 | of kError: # kError does not work via b9 63 | let strLen = v.k.msg.len() 64 | let len = 8 + 2 + strLen 65 | var data = newString(len) 66 | data[0] = 1.char # little endian 67 | data[1] = 2.char # response type 68 | littleEndian64(data[4].addr, len.unsafeAddr) 69 | data[8] = 128.char 70 | copyMem(data[9].addr, v.k.msg, strLen) 71 | data[len-1] = 0.char 72 | socket.send(data) 73 | else: 74 | let data = b9(3, v.k) 75 | data.byteArr[1] = 2 # response type 76 | let sent = socket.send(data.byteArr.addr, data.byteLen.int) 77 | assert sent == data.byteLen 78 | r0(data) 79 | 80 | proc isCall*(x: K0): bool = 81 | (x.kind == KKind.kList or x.kind == kVecSym) and x.len >= 2 82 | 83 | proc isCall*(x: K): bool = 84 | isCall(x.k) 85 | 86 | proc listen*(port: int, timeout = 1000): SocketHandle = 87 | var server = newSocket() 88 | server.setSockOpt(OptReuseAddr, true) 89 | server.bindAddr(Port(port)) 90 | server.listen() 91 | var client = newSocket() 92 | server.accept(client) 93 | let buf = net.recv(client, 3, timeout) 94 | let version = if buf.len() > 1: max(3.byte, buf[^2].byte) else: 0.byte 95 | var bufSend = "_" 96 | bufSend[0] = version.char 97 | send(client, bufSend) 98 | client.getFd() 99 | 100 | 101 | -------------------------------------------------------------------------------- /src/kdb/low/ipc_async.nim: -------------------------------------------------------------------------------- 1 | import asyncnet, asyncdispatch 2 | 3 | import ipc 4 | export ipc 5 | 6 | import endians 7 | 8 | # var clients {.threadvar.}: seq[AsyncSocket] 9 | 10 | type 11 | MessageType* = enum 12 | Async = 0, Sync = 1, Response = 2 13 | 14 | proc handshake*(client: AsyncSocket) {.async} = 15 | let buf = await client.recv(3) 16 | let version = if buf.len() > 1: min(3.byte, buf[^2].byte) else: 0.byte 17 | var bufSend = "_" 18 | bufSend[0] = version.char 19 | await client.send(bufSend) 20 | 21 | import strutils 22 | 23 | proc sendSyncReplyAsync*(client: AsyncSocket, v: K) {.async.} = 24 | case v.kind 25 | of kError: # kError does not work via b9 26 | let strLen = v.k.msg.len() 27 | let len = 8 + 2 + strLen 28 | var data = newString(len) 29 | data[0] = 1.char # little endian 30 | data[1] = 2.char # response type 31 | littleEndian64(data[4].addr, len.unsafeAddr) 32 | data[8] = 128.char 33 | copyMem(data[9].addr, v.k.msg, strLen) 34 | data[len-1] = 0.char 35 | await client.send(data) 36 | else: 37 | let data = b9(3, v.k) 38 | data.byteArr[1] = 2 # response type 39 | await client.send(data.byteArr.addr, data.byteLen.int) 40 | r0(data) 41 | 42 | proc sendAsyncAsync*(client: AsyncSocket, v: K) {.async.} = 43 | let data = b9(3, v.k) 44 | data.byteArr[1] = 0 # async type 45 | await client.send(data.byteArr.addr, data.byteLen.int) 46 | r0(data) 47 | 48 | proc readMessage*(socket: AsyncSocket): Future[(MessageType, K)] {.async.} = 49 | var buf = await socket.recv(8) 50 | var len = 0 51 | littleEndian32(len.addr, buf[4].addr) 52 | buf.add(newString(len - 8)) 53 | let size = await socket.recvInto(buf[8].addr, len - 8) # TODO: add logic to add into buffer 54 | var kBytes = newKVec[byte](len) 55 | copyMem(kBytes.k.byteArr.addr, buf[0].addr, len) 56 | 57 | let k = d9(kBytes.k) 58 | assert not isNil(k) # TODO: check error 59 | result = (MessageType(buf[1].byte), k.toK()) 60 | 61 | proc processMessage(client: AsyncSocket, callback: proc (request: K): K {.closure,gcsafe.}) {.async.} = 62 | let x = await client.readMessage() 63 | 64 | let reply = callback(x[1].toK()) 65 | case x[0] 66 | of Async: await client.sendASyncAsync(reply) # initial request was async 67 | of Sync: await client.sendSyncReplyAsync(reply) # initial request was sync 68 | else: raise newException(KError, "unsupported msg type") 69 | 70 | proc processClient(client: AsyncSocket, 71 | process: proc (client: AsyncSocket, callback: proc (request: K): K {.closure,gcsafe.}): Future[system.void], 72 | callback: proc (request: K): K {.closure,gcsafe.}) {.async.} = 73 | await handshake(client) 74 | while true: 75 | await processMessage(client, callback) 76 | 77 | template createAsyncServe*(processFun: untyped) = 78 | proc asyncServe*(port: uint32, callback: proc (request: K): K {.closure,gcsafe.}) {.async.} = 79 | var server = newAsyncSocket() 80 | server.setSockOpt(OptReuseAddr, true) 81 | server.bindAddr(Port(port)) 82 | server.listen() 83 | 84 | while true: 85 | let client = await server.accept() 86 | echo "connected" 87 | await processClient(client, processFun, callback) 88 | 89 | createAsyncServe(processMessage) 90 | 91 | proc asyncConnect*(hostname: string, port: int): Future[AsyncSocket] {.async.} = 92 | result = newAsyncSocket() 93 | await result.connect(hostname, Port(port)) 94 | await result.send("c\3\0") 95 | discard await result.recv(1) 96 | 97 | proc sendAsync*(socket: AsyncSocket, v: K) {.async.} = 98 | let data = b9(3, v.k) 99 | data.byteArr[1] = 0 # async type 100 | await socket.send(data.byteArr.addr, data.byteLen.int) 101 | r0(data) 102 | 103 | proc asyncRead*(socket: AsyncSocket): Future[K] {.async.} = 104 | result = (await socket.readMessage())[1] 105 | 106 | proc asyncCall*(socket: AsyncSocket, x: string, a: K): Future[K] {.async.} = 107 | var l = newKList() 108 | l.add(x.toK()) 109 | l.add(a) 110 | 111 | let data = b9(3, l.k) 112 | data.byteArr[1] = 1 # sync type 113 | await socket.send(data.byteArr.addr, data.byteLen.int) 114 | r0(data) 115 | result = await asyncRead(socket) 116 | 117 | -------------------------------------------------------------------------------- /src/kdb/low/iters.nim: -------------------------------------------------------------------------------- 1 | 2 | proc `[]`*(x: K0, i: int64): K = 3 | if x.kind != KKind.kDict: 4 | if i >= x.len: 5 | raise newException(KError, "index " & $i & " not in 0 .. " & $(x.len - 1)) 6 | case x.kind 7 | of kVecBool: x.boolArr[i].toK() 8 | of kVecGUID: x.guidArr[i].toK() 9 | of kVecByte: x.byteArr[i].toK() 10 | of kVecShort: x.shortArr[i].toK() 11 | of kVecInt: x.intArr[i].toK() 12 | of kVecLong: x.longArr[i].toK() 13 | of kVecReal: x.realArr[i].toK() 14 | of kVecFloat: x.floatArr[i].toK() 15 | of kVecSym: x.stringArr[i].toSym() 16 | of kVecTimestamp: x.tsArr[i].toKTimestamp() 17 | of kVecMonth: x.monthArr[i].toKMonth() 18 | of kVecDate: x.dateArr[i].toKDate() 19 | of kVecDateTime: x.dtArr[i].toKDateTime() 20 | of kVecTimespan: x.tpArr[i].toKTimespan() 21 | of kVecMinute: x.minuteArr[i].toKMinute() 22 | of kVecSecond: x.secondArr[i].toKSecond() 23 | of kVecTime: x.timeArr[i].toKTime() 24 | of kDict: dictLookup(x, i.toK()) 25 | of kList: x.kArr[i].toK() 26 | else: raise newException(KError, "getFromK0 is not supported for " & $x.kind) 27 | 28 | proc get*[T](x: K0, i: int): T = 29 | when T is K: x[i] 30 | elif T is int64: x.longArr[i] 31 | elif T is int: x.longArr[i].int 32 | elif T is float64: x.floatArr[i] 33 | elif T is cstring: x.stringArr[i] 34 | elif T is string: $x.stringArr[i] 35 | elif T is Sym: Sym(inner: toSym($x.stringArr[i])) # TODO: not sure 36 | else: raise newException(KError, "getK0[" & $T & "] is not supported for " & $x.kind) 37 | 38 | proc getDict*[T, U](x: K, k: T): U = 39 | for i in 0.. 0: 258 | let header = toSymVec(cols.mapIt(it[0])) 259 | let data = %cols.mapIt(newKVecTyped(it[1])) 260 | let dict = newKDict(header, data) 261 | K(k: xT(r1(dict.k))) 262 | else: 263 | K(k: nil) 264 | 265 | proc newKTable*(): K = 266 | K(k: nil) # empty table is nil 267 | # xT(fromDict) 268 | 269 | proc `[]`*(x: K, c: string): K = 270 | assert x.kind == KKind.kTable 271 | dictLookup(x.k.dict, c.toSym()) 272 | 273 | proc `[]=`*(x: var K0, k: K, v: K) = 274 | case x.kind 275 | of kDict: 276 | if x.values.checkAdd(v): 277 | x.keys.add(k) 278 | x.values.add(v) 279 | else: 280 | raise newException(KError, "checkAdd failed for " & $x.values.kind) 281 | else: raise newException(KError, "[K;K;K]`[]=` is not supported for " & $x.kind) 282 | 283 | proc `[]=`*(x: var K, k: K, v: K) = 284 | `[]=`(x.k, k, v) 285 | 286 | proc `[]=`*(x: var K0, i: int64, v: K) = 287 | case x.kind 288 | of kVecFloat: x.floatArr[i] = v.k.ff 289 | else: `[]=`(x, i.toK(), v) 290 | 291 | proc `[]=`*(x: var K, i: int64, v: K) = 292 | `[]=`(x.k, i, v) 293 | 294 | # proc `[]=`*(x: var K, i: SomeInteger, v: K) = 295 | # case x.k.kind 296 | # of kDict: 297 | # x.k.keys.add(i) 298 | # x.k.values.add(v.k) 299 | # of kVecSym: 300 | # assert v.k.kind == kSym # /-------\ 301 | # x.k.stringArr[i] = v.k.ss # TODO: fix 302 | # else: raise newException(KError, "[K;int;K]`[]=` is not supported for " & $x.k.kind) 303 | 304 | proc cols*(x: K): seq[string] = 305 | assert x.kind == KKind.kTable 306 | # result: seq[string] 307 | var cResult: seq[cstring] 308 | cResult.add toOpenArray(x.k.dict.keys.stringArr.addr, 0, x.k.dict.keys.stringLen.int - 1) 309 | cResult.mapIt($it) 310 | 311 | proc dictLookup(d: K0, k: K): K {.gcsafe.} = ## TODO: optimize lookup with additional table 312 | var i = 0 313 | for x in toK(d.keys): 314 | if x == k: 315 | return d.values[i] 316 | inc(i) 317 | raise newException(KeyError, "key not found: " & $k) 318 | -------------------------------------------------------------------------------- /src/kdb/low/types.nim: -------------------------------------------------------------------------------- 1 | # hard to include c-header in nim :) 2 | import os 3 | 4 | {.passC: "-DKXVER=3".} 5 | {.passC: "-I" & currentSourcePath.parentDir().parentDir().parentDir().} 6 | {.link: currentSourcePath.parentDir().parentDir().parentDir().parentDir() & "/c.o".} 7 | {.compile: "k.c".} 8 | 9 | type 10 | KError* = object of ValueError 11 | KErrorRemote* = object of ValueError 12 | 13 | type 14 | KSym* = object 15 | KTimestamp* = object 16 | KDateTime* = object 17 | KList* = object 18 | 19 | type 20 | KKind* {.size: 1.} = enum 21 | kList = 0 22 | kVecBool = 1 23 | kVecGUID = 2 24 | kVecByte = 4 25 | kVecShort = 5 26 | kVecInt = 6 27 | kVecLong = 7 28 | kVecReal = 8 29 | kVecFloat = 9 30 | kVecChar = 10 31 | kVecSym = 11 32 | kVecTimestamp = 12 33 | kVecMonth = 13 34 | kVecDate = 14 35 | kVecDateTime = 15 36 | kVecTimespan = 16 37 | kVecMinute = 17 38 | kVecSecond = 18 39 | kVecTime = 19 40 | kTable = 98 41 | kDict = 99 42 | kId = 101 43 | kError = 128 44 | kTime = 256-19 45 | kSecond = 256-18 46 | kMinute = 256-17 47 | kTimespan = 256-16 48 | kDateTime = 256-15 49 | kDate = 256-14 50 | kMonth = 256-13 51 | kTimestamp = 256-12 52 | kSym = 256-11 53 | kChar = 256-10 54 | kFloat = 256-9 55 | kReal = 256-8 56 | kLong = 256-7 57 | kInt = 256-6 58 | kShort = 256-5 59 | kByte = 256-4 60 | kGUID = 256-2 61 | kBool = 256-1 62 | 63 | GUID* {.importc: "U", header: "k.h".} = object 64 | g* {.importc.}: array[16, byte] 65 | 66 | K0* = ptr object {.packed.} 67 | m*: cchar 68 | a*: cchar 69 | case kind*: KKind 70 | of kList: 71 | lu: cchar 72 | lr: cint 73 | kLen*: int64 74 | kArr*: UncheckedArray[K0] 75 | of kVecBool: 76 | vbu: cchar 77 | vbr: cint 78 | boolLen*: int64 79 | boolArr*: UncheckedArray[bool] 80 | of kVecGUID: 81 | vgu: cchar 82 | vgr: cint 83 | guidLen*: int64 84 | guidArr*: UncheckedArray[GUID] 85 | of kVecByte: 86 | vyu: cchar 87 | vyr: cint 88 | byteLen*: int64 89 | byteArr*: UncheckedArray[byte] 90 | of kVecShort: 91 | vhu: cchar 92 | vhr: cint 93 | shortLen*: int64 94 | shortArr*: UncheckedArray[int16] 95 | of kVecInt: 96 | viu: cchar 97 | vir: cint 98 | intLen*: int64 99 | intArr*: UncheckedArray[int32] 100 | of kVecLong: 101 | vju: cchar 102 | vjr: cint 103 | longLen*: int64 104 | longArr*: UncheckedArray[int64] 105 | of kVecReal: 106 | vru: cchar 107 | vrr: cint 108 | realLen*: int64 109 | realArr*: UncheckedArray[float32] 110 | of kVecFloat: 111 | vfu: cchar 112 | vfr: cint 113 | floatLen*: int64 114 | floatArr*: UncheckedArray[float64] 115 | of kVecChar: 116 | vcu: cchar 117 | vcr: cint 118 | charLen*: int64 119 | charArr*: UncheckedArray[char] 120 | of kVecSym: 121 | vsu: cchar 122 | vsr: cint 123 | stringLen*: int64 124 | stringArr*: UncheckedArray[cstring] 125 | of kVecTimestamp: 126 | vtsu: cchar 127 | vtsr: cint 128 | tsLen*: int64 129 | tsArr*: UncheckedArray[int64] 130 | of kVecMonth: 131 | vmu: cchar 132 | vmr: cint 133 | monthLen*: int64 134 | monthArr*: UncheckedArray[int32] 135 | of kVecDate: 136 | vdu: cchar 137 | vdr: cint 138 | dateLen*: int64 139 | dateArr*: UncheckedArray[int32] 140 | of kVecDateTime: 141 | vdtu: cchar 142 | vdtr: cint 143 | dtLen*: int64 144 | dtArr*: UncheckedArray[float64] 145 | of kVecTimespan: 146 | vtpu: cchar 147 | vtpr: cint 148 | tpLen*: int64 149 | tpArr*: UncheckedArray[int64] 150 | of kVecMinute: 151 | vmiu: cchar 152 | vmir: cint 153 | minuteLen*: int64 154 | minuteArr*: UncheckedArray[int32] 155 | of kVecSecond: 156 | vseu: cchar 157 | vser: cint 158 | secondLen*: int64 159 | secondArr*: UncheckedArray[int32] 160 | of kVecTime: 161 | vttu: cchar 162 | vttr: cint 163 | timeLen*: int64 164 | timeArr*: UncheckedArray[int32] 165 | of kTable: 166 | tu*: cchar 167 | tr*: cint 168 | dict*: K0 169 | of kDict: 170 | du: cchar 171 | dr: cint 172 | dn*: int64 # always 2 173 | keys*: K0 174 | values*: K0 175 | of kId: 176 | idu: cchar 177 | idr: cint 178 | idg*: byte 179 | of kError: 180 | eru: cchar 181 | err: cint 182 | msg*: cstring 183 | of kTime: 184 | ttu: cchar 185 | ttr: cint 186 | tt*: int32 187 | of kSecond: 188 | seu: cchar 189 | ser: cint 190 | se*: int32 191 | of kMinute: 192 | miu: cchar 193 | mir: cint 194 | mi*: int32 195 | of kTimespan: 196 | tpu: cchar 197 | tpr: cint 198 | tp*: int64 199 | of kDateTime: 200 | dtu: cchar 201 | dtr: cint 202 | dt*: float64 203 | of kDate: 204 | eu: cchar 205 | er: cint 206 | dd*: int32 207 | of kMonth: 208 | mu: cchar 209 | mr: cint 210 | mo*: int32 211 | of kTimestamp: 212 | tsu: cchar 213 | tsr: cint 214 | ts*: int64 215 | of kSym: 216 | su: cchar 217 | sr: cint 218 | ss*: cstring 219 | of kChar: 220 | cu: cchar 221 | cr: cint 222 | ch*: char 223 | of kFloat: 224 | fu: cchar 225 | fr: cint 226 | ff*: float64 227 | of kReal: 228 | rru: cchar 229 | rrr: cint 230 | rr*: float32 231 | of kLong: 232 | ju: cchar 233 | jr: cint 234 | jj*: int64 235 | of kInt: 236 | iu: cchar 237 | ir: cint 238 | ii*: int32 239 | of kShort: 240 | hu: cchar 241 | hr: cint 242 | sh*: int16 243 | of kByte: 244 | yu: cchar 245 | yr: cint 246 | by*: byte 247 | of kGUID: 248 | gu: cchar 249 | gr: cint 250 | gn*: clonglong # probably 2 251 | gg*: GUID 252 | of kBool: 253 | bu: cchar 254 | br: cint 255 | bb*: bool 256 | 257 | K* = object 258 | k*: K0 259 | 260 | proc r0*(x: K0) {. 261 | importc: "r0", header: "k.h".} 262 | 263 | proc r1*(x: K0): K0 {. 264 | importc: "r1", header: "k.h".} 265 | 266 | proc `=destroy`*(x: var K) = 267 | if x.k != nil: 268 | # let rc = cast[ptr UncheckedArray[cint]](x.k)[1] 269 | # echo "destroy K: ", x.k.kind, " rc = ", rc, " addr = " # , repr(x.k) 270 | r0(x.k) 271 | 272 | proc `=`*(a: var K, b: K) = 273 | # echo "`=`" 274 | `=destroy`(a) 275 | a.k = r1(b.k) 276 | 277 | proc `=sink`*(a: var K; b: K) = 278 | # echo "`=sink`" 279 | `=destroy`(a) 280 | a.k = b.k 281 | -------------------------------------------------------------------------------- /tests/basic.nim: -------------------------------------------------------------------------------- 1 | import kdb/low 2 | 3 | test "simple_atoms": 4 | check (%true).kind == KKind.kBool 5 | check (%10.byte).kind == KKind.kByte 6 | check (%10.int16).kind == KKind.kShort 7 | check (%10.int32).kind == KKind.kInt 8 | check (%10.int).kind == KKind.kLong 9 | check (%10.int64).kind == KKind.kLong 10 | check (%10.float32).kind == KKind.kReal 11 | check (%10.float).kind == KKind.kFloat 12 | check (%10.float64).kind == KKind.kFloat 13 | check (%'a').kind == KKind.kChar 14 | check toSym("aaa").kind == KKind.kSym 15 | check s"aaa".kind == KKind.kSym 16 | 17 | test "guid": 18 | let guid1 = %[10.byte,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1] 19 | check guid1.kind == KKind.kGUID 20 | let guidStr = "0a000000-0000-0000-0000-000000000001" 21 | let guid2 = toGUID(guidStr) 22 | check guid2.kind == KKind.kGUID 23 | check guid1.k.gg == guid2.k.gg 24 | check $guid1 == guidStr 25 | 26 | test "vectors": 27 | var v = newKVec[int]() 28 | check v.kind == KKind.kVecLong 29 | try: 30 | v.add(false) 31 | check false 32 | except: 33 | check true 34 | v.add(10) 35 | v.add(20) 36 | check v[0] == %10 37 | check v[1] == %20 38 | check v.len == 2 39 | 40 | test "simple_lists": 41 | var l = newKList() 42 | l.add(false) 43 | l.add(10) 44 | check l.len == 2 45 | check l[0] == %false 46 | check l[1] == %10 47 | 48 | test "list_of_vecs": 49 | var v1 = newKVec[bool]() 50 | v1.add(false) 51 | v1.add(true) 52 | var v2 = newKVec[int]() 53 | v2.add(10) 54 | var l2 = newKList() 55 | l2.add(100) 56 | var l = newKList() 57 | l.add(v1) 58 | l.add(v2) 59 | l.add(l2) 60 | check $l == "([false, true]; [10]; (100))" 61 | 62 | test "dicts_simple": 63 | var d = newKDict[int, string]() 64 | d[1] = %"one" 65 | d[10] = %"ten" 66 | check d[10] == %"ten" 67 | try: 68 | discard d[11] 69 | check false 70 | except: 71 | check true 72 | check d.len == 2 73 | check $d == """{1: "one"; 10: "ten"}""" 74 | 75 | var dd = newKDict[int, Ksym]() 76 | try: 77 | dd[1] = %"one" 78 | check false 79 | except: 80 | check true 81 | dd[2] = s"two" 82 | dd[10] = s"ten" 83 | check $dd == "{2: two; 10: ten}" 84 | 85 | var ddd = newKDict[int, nil]() 86 | ddd[1] = %111 87 | ddd[10] = %"ten" 88 | check $ddd == """{1: 111; 10: "ten"}""" 89 | 90 | test "dict_of_dict": 91 | var d = newKDict[nil, string]() 92 | var d1 = newKDict[int, KSym]() 93 | d1[1] = s"one" 94 | d1[2] = s"two" 95 | var d2 = newKDict[int, string]() 96 | d2[11] = %"eleven" 97 | d[d1] = %"11" 98 | d[d2] = %"22" 99 | check $d == """{{1: one; 2: two}: "11"; {11: "eleven"}: "22"}""" 100 | 101 | test "tables_simple": 102 | var t = newKTable() 103 | check t.len == 0 104 | t.addColumn[:int]("aaa") 105 | t.addColumn[:string]("bbb") 106 | check t.len == 0 107 | t.addRow(%3, %"30") 108 | t.addRow(%4, %"40") 109 | t.addRow(%5, %"50") 110 | check t.len == 3 111 | check t.flatoKTable() == """|aaa: [3, 4, 5], bbb: ("30"; "40"; "50")|""" 112 | 113 | var tt = newKTable() 114 | tt.addColumn[:GUID]("id") 115 | tt.addColumn[:KSym]("nick") 116 | tt.addColumn[:string]("name") 117 | tt.addRow("0a000000-0000-0000-0000-000000000001".toGUID(), s"nick1", %"name1") 118 | tt.addRow("0a000000-0000-0000-0000-000000000002".toGUID(), s"nick2", %"name2") 119 | tt.addRow("0a000000-0000-0000-0000-000000000003".toGUID(), s"nick3", %"name3") 120 | tt.addRow("0a000000-0000-0000-0000-000000000004".toGUID(), s"nick4", %"name4") 121 | let tStr = tt.flatoKTable() 122 | check tStr.startsWith "|id: [0a000000-0000-0000-0000-000000000001, 0a000000-" 123 | check tStr.contains "nick: [nick1, nick2, nick3, nick4]" 124 | check tStr.contains """name: ("name1"; "name2"; "name3"; "name4")|""" 125 | 126 | test "table_del": 127 | var t = newKTable() 128 | t.addColumn[:int]("aaa") 129 | t.addColumn[:string]("bbb") 130 | t.addRow(%3, %"30") 131 | t.addRow(%4, %"40") 132 | t.addRow(%5, %"50") 133 | t.deleteColumn("aaa") 134 | check t.flatoKTable() == """|bbb: ("30"; "40"; "50")|""" 135 | 136 | test "iterators": 137 | var t = newKVec[KSym]() 138 | t.add(s"aa") 139 | t.add(s"bb") 140 | t.add(s"cc") 141 | var str = "" 142 | for x in t: 143 | str.add $x 144 | check str == "aabbcc" 145 | 146 | str = "" 147 | for i, x in t: 148 | str.add $i & ":" & $x 149 | check str == "0:aa1:bb2:cc" 150 | 151 | var l = newKList() 152 | l.add(10) 153 | l.add(20) 154 | l.add(30) 155 | str = "" 156 | for x in l: 157 | str.add $x 158 | check str == "102030" 159 | 160 | var d = newKDict[int, KSym]() 161 | d[1] = s"one" 162 | d[2] = s"two" 163 | str = "" 164 | for k, v in d: 165 | str.add $k & ":" & $v 166 | check str == "1:one2:two" 167 | 168 | test "times": 169 | var v = newKVec[KTimestamp]() 170 | let ts = getTime() 171 | v.add(%ts) 172 | v.add(%ts) 173 | check v.len == 2 174 | check v[0].kind == KKind.kTimestamp 175 | check v[0] == %ts 176 | check v[1] == %ts 177 | 178 | var vv = newKVec[KDateTime]() 179 | let dt = now().utc() 180 | vv.add(%dt) 181 | vv.add(%dt) 182 | check vv[0].kind == KKind.kDateTime 183 | check vv[0] == %dt 184 | check vv[1] == %dt 185 | 186 | test "amend": 187 | var v = newKVec[float]() 188 | v.add(10.1) 189 | v.add(11.2) 190 | v.add(12.3) 191 | v[0] = %110.1 192 | v[2] = %112.3 193 | check $v == "[110.1, 11.2, 112.3]" 194 | 195 | test "seq": 196 | let v = %[10.1, 11.2, 12.3] 197 | check $v == "[10.1, 11.2, 12.3]" 198 | var vv = %[10.1, 111.2, 12.3] 199 | check v != vv 200 | vv[1] = 11.2.toK() 201 | check v == vv 202 | 203 | test "list_seq": 204 | var l = newKList() 205 | let dt = now().utc() 206 | l.add %[1] # TODO: cannot implicit convert 207 | l.add %[4, 5] 208 | l.add %[7, 8, 9] 209 | l.add %[10.0, 11.0, 12.0, 13.0] 210 | l.add %[dt, dt] 211 | check $l == "([1]; [4, 5]; [7, 8, 9]; [10.0, 11.0, 12.0, 13.0]; [" & $ %dt & ", " & $ %dt & "])" 212 | 213 | test "tables_from": 214 | var tNil = newKTable() 215 | tNil.addColumn[:int64]("aaa", %[1,2,3]) 216 | check tNil.len == 3 217 | 218 | var t = newKTable({"aaa": KKind.kLong, "bbb": KKind.kList}) 219 | t.addRow(%1, 220 | %[ 221 | %[1,2,3], 222 | %[4,5,6] 223 | ] 224 | ) 225 | 226 | try: 227 | t.addColumn[:int64]("ccc", %[%2, %[1,2,3]]) 228 | check false 229 | except: 230 | check true 231 | 232 | try: 233 | t.addColumn[:int64]("ccc", %[1,2,3]) 234 | check false 235 | except: 236 | check true 237 | 238 | test "tables_idx": 239 | var t = newKTable() 240 | t.addColumn[:int64]("aaa", %[1,2,3]) 241 | t.addColumn[:string]("bbb", %["aaa", "bbb", "ccc"]) 242 | t.addColumn[:KSym]("ccc", ["aaa", "bbb", "ccc"].toSymVec()) 243 | check t.len == 3 244 | 245 | try: 246 | discard t["zzz"] 247 | check false 248 | except: 249 | check true 250 | 251 | check t["aaa"][0] == %1 252 | check t["bbb"][2] == %"ccc" 253 | check t["ccc"][1] == s"bbb" 254 | 255 | import tables 256 | import sequtils 257 | 258 | test "table_cols": 259 | const map = {1: "one", 2: "two", 3:"three"}.toTable 260 | 261 | var t = newKTable() 262 | t.addColumn[:int64]("a", %[1, 2, 3, 4]) 263 | 264 | var c1 = (0.. %10 279 | check b >= %10 280 | check b == %12 281 | let c = b * %2 282 | check c == %24 283 | check -c == % -24 284 | var f = %2.5 285 | check (f*(%2.0)) == %5.0 286 | f += %10.0 287 | check f == %12.5 288 | f *= %2.0 289 | check f == %25.0 290 | 291 | test "mitems": 292 | var a = %[10, 20, 30] 293 | for x in a.mitems[:int64]: 294 | x *= 2 295 | check a == %[20, 40, 60] 296 | 297 | var b = %[10.1, 20.2, 30.3] 298 | for x in b.mitems[:float64]: 299 | x *= 2 300 | check b == %[20.2, 40.4, 60.6] 301 | 302 | var c = ["aa", "bb", "cc"].toSymVec() 303 | for x in c.mitems[:cstring]: 304 | x = ($x & $x).cstring 305 | check c == ["aaaa", "bbbb", "cccc"].toSymVec() 306 | 307 | var d = %["aa", "bb", "cc"] 308 | for x in c.mitems[:cstring]: 309 | x = ($x & $x) 310 | check d == %["aa", "bb", "cc"] # TODO: check 311 | 312 | test "getters": 313 | check toK(true).getBool() == true 314 | let guid = genUUID() 315 | check toK(guid).getGUID() == guid 316 | check toK(10.int16).getInt16() == 10.int16 317 | check toK(10.int32).getInt32() == 10.int32 318 | check toK(10.int64).getInt() == 10.int64 319 | check toK(10).getInt64() == 10 320 | check toK(10.1.float32).getFloat32() == 10.1.float32 321 | check toK(10.1.float64).getFloat64() == 10.1.float64 322 | check toK(10.1).getFloat() == 10.1 323 | check (s"test").getStr() == "test" 324 | check toK("test").getStr() == "test" 325 | let ts = getTime() 326 | check toK(ts).getTime() == ts 327 | var dt = now().utc() 328 | dt.nanosecond = 0 329 | check toK(dt).getDateTime() == dt 330 | 331 | test "iterators_specialized": 332 | let v = %[10, 20] 333 | var i = 1 334 | for x in v.items(int64): 335 | check x == i * 10 336 | inc(i) 337 | for i, x in v.pairs(int64): 338 | check x == (i+1) * 10 339 | 340 | let sSym = ["aaa", "bbb"].toSymVec() 341 | check toSeq(sSym.items(string)) == @["aaa", "bbb"] 342 | 343 | 344 | -------------------------------------------------------------------------------- /tests/config.nims: -------------------------------------------------------------------------------- 1 | switch("path", "$projectDir/../src") -------------------------------------------------------------------------------- /tests/extended.nim: -------------------------------------------------------------------------------- 1 | import kdb 2 | 3 | type 4 | T1 = object of RootObj 5 | k: int64 6 | v: string 7 | 8 | T2 = object 9 | k, v: int 10 | 11 | T11 = object of T1 12 | vv: float 13 | 14 | T111 = object of T11 15 | vvv: string 16 | 17 | T3 = object 18 | v: string 19 | 20 | T4 = object of T1 21 | s: Sym 22 | 23 | # T4 = object 24 | # k: int64 25 | # v: seq[int64] 26 | 27 | defineTable(T1) 28 | 29 | defineTable(T2) 30 | 31 | defineTable(T11) 32 | 33 | defineTable(T111) 34 | 35 | defineTable(T4) 36 | 37 | test "vec": 38 | var t = kdb.newKVec[int64]() 39 | t.add(10) 40 | t.add(20) 41 | check toSeq(t) == @[10.int64, 20] 42 | 43 | test "vec_of_vec": 44 | var v = kdb.newKVec[seq[int64]]() 45 | v.add(@[10.int64, 20]) 46 | v.add(@[30.int64, 40, 50]) 47 | check v.len() == 2 48 | check v[0].len() == 2 49 | check v[1].len() == 3 50 | var v1 = v[1] 51 | check compiles(v1.add(60.6)) == false 52 | v1.add(60) 53 | check v[1].len() == 4 54 | 55 | test "vec_of_vec_of_vec": 56 | var v = kdb.newKVec[seq[seq[int64]]]() 57 | v.add(@[@[10.int64], @[20.int64, 30]]) 58 | v.add(@[@[40.int64, 50], @[60.int64]]) 59 | 60 | test "dict": 61 | var d = kdb.newKDict[int, float]() 62 | d[1] = 1.1 63 | d[2] = 2.2 64 | d[1] = 3.3 65 | echo d 66 | var dd = kdb.newKDict[int, string]() 67 | dd[1] = "onn" 68 | dd[2] = "two" 69 | dd[1] = "one" 70 | echo dd 71 | 72 | test "dict_of_vec": 73 | var d = kdb.newKDict[int, seq[float]]() 74 | d[1] = @[1.1, 11.1] 75 | d[2] = @[2.2, 22.2] 76 | 77 | test "table": 78 | var t = newKTable(T1) 79 | t.add(T1(k: 1, v: "one")) 80 | t.add(T1(k: 2, v: "two")) 81 | # discard r1(t.inner.k.dict.values.kArr) 82 | check t.len == 2 83 | check compiles(t.add(T1(k: 11, v: "oneone"))) == true 84 | check compiles(t.add(T2(k: 10, v: 20))) == false 85 | check toSeq(t.k.pairs()) == @[(0, 1.int64), (1, 2.int64)] 86 | check t.k.mapIt(it + 10) == @[11.int64, 12] 87 | check compiles(t.k.mapIt(it + "abc")) == false 88 | var k = t.k 89 | for x in k.mitems(): 90 | x += 100 91 | var v = t.v 92 | check toSeq(t.k) == @[101.int64, 102] 93 | 94 | test "table_transforms_with_default": 95 | var t = newKTable(T1) 96 | t.add(T1(k: 1, v: "one")) 97 | check t.cols() == @["k", "v"] 98 | check compiles(t.vv) == false 99 | 100 | var tt = t.transform(T11) 101 | tt.add(T11(k: 2, v: "two", vv: 2.2)) 102 | check tt.cols() == @["k", "v", "vv"] 103 | check tt.vv[0] == 0.0 # default value 104 | check tt.vv[1] == 2.2 105 | 106 | try: 107 | echo t 108 | check false 109 | except: 110 | check true 111 | 112 | var ttt = tt.transform(T3) 113 | check ttt.cols() == @["v"] 114 | 115 | test "table_transforms_with_vec": 116 | var t = newKTable(T1) 117 | t.add(T1(k: 1, v: "one")) 118 | t.add(T1(k: 2, v: "two")) 119 | check t.cols() == @["k", "v"] 120 | check compiles(t.vv) == false 121 | 122 | let tt = t.transform(T11, @[1.1, 2.2]) 123 | check tt.cols() == @["k", "v", "vv"] 124 | check tt.vv[0] == 1.1 125 | check tt.vv[1] == 2.2 126 | 127 | # test "table_of_vec": 128 | # var t = newKTable(T4) 129 | 130 | test "sym": 131 | var t = newKTable(T1) 132 | t.add(T1(k: 1, v: "one")) 133 | t.add(T1(k: 2, v: "two")) 134 | let tt = t.transform(T4, [s"one", s"two"]) 135 | check tt.s[0] == s"one" 136 | check tt.s[1] == s"two" 137 | 138 | test "sym_string": 139 | var t = newKTable(T1) 140 | t.add(T1(k: 1, v: "one")) 141 | t.add(T1(k: 2, v: "two")) 142 | var tt = t.transform(T4, ["one", "two"]) 143 | check tt.s[0] == "one" 144 | check tt.s[1] == "two" 145 | tt.add(T4(k: 3, v: "three", s: "three")) 146 | check tt.s[2] == s"three" 147 | 148 | -------------------------------------------------------------------------------- /tests/extended_ipc.nim: -------------------------------------------------------------------------------- 1 | 2 | import os 3 | import asyncdispatch 4 | 5 | type 6 | ReqT = object 7 | x: int64 8 | ResT = object 9 | x: float64 10 | ReqTErr1 = object 11 | x: float 12 | ReqTErr2 = object 13 | y: float 14 | 15 | defineTable(ReqT) 16 | defineTable(ResT) 17 | defineTable(ReqTErr1) 18 | defineTable(ReqTErr2) 19 | 20 | test "test_ipc": 21 | proc server() {.gcsafe.} = 22 | let client = listen(9999) 23 | var (call, data) = client.read(ReqT) 24 | check call == "test" 25 | var c = data.x 26 | for x in c.mitems(): 27 | x *= 10 28 | client.reply(data) 29 | 30 | var worker1: Thread[void] 31 | createThread(worker1, server) 32 | 33 | sleep(20) 34 | 35 | let h = connect("localhost", 9999) 36 | check true 37 | var t = newKTable(ReqT) 38 | t.add(ReqT(x: 1)) 39 | t.add(ReqT(x: 2)) 40 | t.add(ReqT(x: 3)) 41 | let response = h.callTable[:ReqT]("test", t, check = true) 42 | check toSeq(response.x) == @[10.int64, 20, 30] 43 | 44 | worker1.joinThread() 45 | 46 | test "test_ipc_high_check": 47 | proc server() {.gcsafe.} = 48 | let client = listen(9998) 49 | try: 50 | var (call, data) = client.read(ReqTErr1) 51 | check false 52 | except: 53 | check true 54 | 55 | var t = newKTable(ReqTErr1) 56 | client.reply(t) 57 | 58 | var worker1: Thread[void] 59 | createThread(worker1, server) 60 | 61 | sleep(20) 62 | 63 | let h = connect("localhost", 9998) 64 | check true 65 | var t = newKTable(ReqT) 66 | try: 67 | let response = h.callTable[:ReqTErr2]("test", t, check = true) 68 | check false 69 | except: 70 | check true 71 | 72 | worker1.joinThread() 73 | 74 | test "test_ipc_async_server": 75 | serve(9997): 76 | proc test1(x: KTable[ReqT]): KTable[ResT] {.gcsafe.} = 77 | result = newKTable(ResT) 78 | for x in x.x: 79 | result.add(ResT(x: 11 * x.float + x.float / 10.0)) 80 | proc test2(x: KTable[ResT]): KTable[ReqT] {.gcsafe.} = 81 | result = newKTable(ReqT) 82 | for x in x.x: 83 | result.add(ReqT(x: 10 * x.int)) 84 | 85 | let h = waitFor asyncConnect("localhost", 9997) 86 | check true 87 | 88 | var t = newKTable(ReqT) 89 | t.add(ReqT(x: 1)) 90 | t.add(ReqT(x: 2)) 91 | t.add(ReqT(x: 3)) 92 | let response = waitFor h.asyncCallTable[:ReqT, ResT]("test1", t, check = true) 93 | check toSeq(response.x) == @[11.1.float, 22.2, 33.3] 94 | 95 | var t2 = newKTable(ResT) 96 | t2.add(ResT(x: 1.1)) 97 | t2.add(ResT(x: 2.2)) 98 | t2.add(ResT(x: 3.3)) 99 | let response2 = waitFor h.asyncCallTable[:ResT, ReqT]("test2", t2, check = true) 100 | check toSeq(response2.x) == @[10.int64, 20, 30] 101 | 102 | test "test_ipc_async_client": 103 | proc server() {.gcsafe.} = 104 | let client = listen(9996) 105 | 106 | var t = newKTable(ReqT) 107 | t.add(ReqT(x: 1)) 108 | t.add(ReqT(x: 2)) 109 | t.add(ReqT(x: 3)) 110 | 111 | let resp = client.callTable[:ResT]("test1", t.inner) 112 | check toSeq(resp.x) == @[1.0, 2.0, 3.0] 113 | 114 | var worker1: Thread[void] 115 | createThread(worker1, server) 116 | 117 | sleep(20) 118 | 119 | let client = waitFor asyncConnect("localhost", 9996) 120 | check true 121 | 122 | serveOne(client): 123 | proc test1(x: KTable[ReqT]): KTable[ResT] {.gcsafe.} = 124 | check toSeq(x.x) == @[1.int64, 2, 3] 125 | result = newKTable(ResT) 126 | for x in x.x: 127 | result.add(ResT(x: x.float)) 128 | 129 | test "test_ipc_async_error": 130 | proc server() {.gcsafe.} = 131 | let client = listen(9995) 132 | 133 | var t = newKTable(ReqT) 134 | t.add(ReqT(x: 1)) 135 | t.add(ReqT(x: 2)) 136 | t.add(ReqT(x: 3)) 137 | 138 | try: 139 | let resp = client.callTable[:ResT]("test2", t.inner) 140 | check false 141 | except KErrorRemote: 142 | check "test2" == getCurrentExceptionMsg() 143 | 144 | var worker1: Thread[void] 145 | createThread(worker1, server) 146 | 147 | sleep(20) 148 | 149 | let client = waitFor asyncConnect("localhost", 9995) 150 | check true 151 | 152 | serveOne(client): 153 | proc test1(x: KTable[ReqT]): KTable[ResT] {.gcsafe.} = 154 | check toSeq(x.x) == @[1.int64, 2, 3] 155 | result = newKTable(ResT) 156 | for x in x.x: 157 | result.add(ResT(x: x.float)) 158 | -------------------------------------------------------------------------------- /tests/mem.nim: -------------------------------------------------------------------------------- 1 | 2 | test "testMem": 3 | while true: 4 | var t = newKTable() 5 | t.addColumn[:int64]("aaa") 6 | t.addColumn[:nil]("bbb") 7 | t.addRow(%3, %"30") 8 | t.addRow(%4, %"40") 9 | t.addRow(%5, %"50") 10 | echo t 11 | var i = %1122 12 | var d = newKDict[int, nil]() 13 | d[1] = %"one" 14 | d[2] = %"two" 15 | echo d 16 | var dd = newKDict[int, int64]() 17 | dd[1] = %11 18 | dd[2] = %22 19 | echo dd 20 | var l = newKList() 21 | l.add(%"aa".cstring) 22 | echo l 23 | var v1 = low.newKVec[int]() 24 | v1.add(10) 25 | v1.add(20) 26 | var v2 = low.newKVec[KSym]() 27 | v2.add("100") 28 | v2.add("200") 29 | var v3 = low.newKVec[nil]() 30 | v3.add("100") 31 | v3.add("200") 32 | echo v3 33 | var vv = low.newKList() 34 | vv.add(v1) 35 | vv.add(v2) 36 | for x in vv: 37 | for y in x: 38 | echo y 39 | echo vv 40 | 41 | # test "testMemFailed": 42 | # for i in 0..100: 43 | # echo "DEBUG1" 44 | # let vv = K(k: knk(0)) 45 | # for i in vv.k: 46 | # discard 47 | # let x = K(k: ktn(11, 0)) 48 | # echo "DEBUG2" 49 | 50 | -------------------------------------------------------------------------------- /tests/remote.nim: -------------------------------------------------------------------------------- 1 | # test "testRemote": 2 | # let h = connect("test-kdb", 9999) 3 | # check h > 0 4 | # let result = h.exec0("test") 5 | # echo result 6 | 7 | import tables 8 | import sequtils 9 | import os 10 | import asyncdispatch 11 | 12 | test "test_ipc_sync": 13 | proc server() {.gcsafe.} = 14 | let client = listen(9999) 15 | let d = low.read(client) 16 | check isCall(d) 17 | check d[0] == %"test" 18 | var t = d[1] 19 | for x in t.mitems[:int64]: 20 | x *= 2 21 | client.sendSyncReply(t) 22 | 23 | var worker1: Thread[void] 24 | createThread(worker1, server) 25 | 26 | sleep(20) 27 | 28 | let h = connect("localhost", 9999) 29 | check true 30 | let response = exec(h, "test", %[10, 20, 30]) 31 | check response == %[20, 40, 60] 32 | 33 | worker1.joinThread() 34 | 35 | test "test_ipc_sendasync": 36 | proc server() {.gcsafe.} = 37 | let client = listen(9998) 38 | var t = low.read(client) 39 | for x in t.mitems[:int64]: 40 | x *= 2 41 | client.sendASync(t) 42 | 43 | var worker1: Thread[void] 44 | createThread(worker1, server) 45 | 46 | sleep(20) 47 | 48 | let h = connect("localhost", 9998) 49 | check true 50 | h.sendASync(%[10, 20, 30]) 51 | let response = h.read() 52 | check response == %[20, 40, 60] 53 | 54 | worker1.joinThread() 55 | 56 | test "test_ipc_async": 57 | proc server() {.gcsafe.} = 58 | proc f(x: K): K = 59 | check isCall(x) 60 | check x[0] == %"test" 61 | result = x[1] 62 | for x in result.mitems[:int64]: 63 | x *= 2 64 | 65 | waitFor asyncServe(9997, f) 66 | 67 | var worker1: Thread[void] 68 | createThread(worker1, server) 69 | 70 | sleep(20) 71 | 72 | let h = waitFor asyncConnect("localhost", 9997) 73 | check true 74 | let response = waitFor h.asyncCall("test", %[10, 20, 30]) 75 | check response == %[20, 40, 60] 76 | 77 | # worker1.joinThread() 78 | -------------------------------------------------------------------------------- /tests/test_1_low.nim: -------------------------------------------------------------------------------- 1 | # This is just an example to get you started. You may wish to put all of your 2 | # tests into a single file, or separate them into multiple `test1`, `test2` 3 | # etc. files (better names are recommended, just make sure the name starts with 4 | # the letter 't'). 5 | # 6 | # To run these tests, simply execute `nimble test`. 7 | 8 | {.passC: "-Isrc".} 9 | 10 | import unittest 11 | 12 | import strutils 13 | import times 14 | import uuids 15 | import sequtils 16 | 17 | include basic 18 | # include extended 19 | 20 | # include mem 21 | 22 | include remote 23 | -------------------------------------------------------------------------------- /tests/test_2_high.nim: -------------------------------------------------------------------------------- 1 | {.passC: "-Isrc".} 2 | 3 | import unittest 4 | 5 | import sequtils 6 | 7 | include extended 8 | 9 | include extended_ipc 10 | --------------------------------------------------------------------------------