|
| 1 | +package tink.sql.drivers.node; |
| 2 | + |
| 3 | +import haxe.Int64; |
| 4 | +import js.node.stream.Readable.Readable; |
| 5 | +import haxe.DynamicAccess; |
| 6 | +import haxe.io.Bytes; |
| 7 | +import tink.sql.Query; |
| 8 | +import tink.sql.Info; |
| 9 | +import tink.sql.Types; |
| 10 | +import tink.sql.format.Sanitizer; |
| 11 | +import tink.streams.Stream; |
| 12 | +import tink.sql.format.CockroachDbFormatter; |
| 13 | +import tink.sql.drivers.node.PostgreSql; |
| 14 | +import tink.sql.drivers.node.externs.PostgreSql; |
| 15 | + |
| 16 | +import #if haxe3 js.lib.Error #else js.Error #end as JsError; |
| 17 | + |
| 18 | +using tink.CoreApi; |
| 19 | + |
| 20 | +class CockroachDb implements Driver { |
| 21 | + public final type:Driver.DriverType = CockroachDb; |
| 22 | + |
| 23 | + final settings:PostgreSqlNodeSettings; |
| 24 | + |
| 25 | + public function new(settings) { |
| 26 | + this.settings = settings; |
| 27 | + } |
| 28 | + |
| 29 | + public function open<Db>(name:String, info:DatabaseInfo):Connection.ConnectionPool<Db> { |
| 30 | + final pool = new Pool({ |
| 31 | + user: settings.user, |
| 32 | + password: settings.password, |
| 33 | + host: settings.host, |
| 34 | + port: switch (settings.port) { |
| 35 | + case null: 26257; |
| 36 | + case v: v; |
| 37 | + }, |
| 38 | + ssl: settings.ssl, |
| 39 | + max: switch settings.max { |
| 40 | + case null: 1; |
| 41 | + case v: v; |
| 42 | + }, |
| 43 | + database: name, |
| 44 | + }); |
| 45 | + |
| 46 | + return new CockroachDbConnectionPool(info, pool); |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +class CockroachDbConnectionPool<Db> implements Connection.ConnectionPool<Db> { |
| 51 | + final pool:Pool; |
| 52 | + final info:DatabaseInfo; |
| 53 | + final formatter:CockroachDbFormatter; |
| 54 | + final parser:PostgreSqlResultParser<Db>; |
| 55 | + final streamBatch:Int = 50; |
| 56 | + |
| 57 | + public function new(info, pool) { |
| 58 | + this.info = info; |
| 59 | + this.pool = pool; |
| 60 | + this.formatter = new CockroachDbFormatter(); |
| 61 | + this.parser = new PostgreSqlResultParser(); |
| 62 | + } |
| 63 | + |
| 64 | + public function getFormatter() |
| 65 | + return formatter; |
| 66 | + |
| 67 | + public function execute<Result>(query:Query<Db, Result>):Result { |
| 68 | + final cnx = getNativeConnection(); |
| 69 | + return new CockroachDbConnection(info, cnx, true).execute(query); |
| 70 | + } |
| 71 | + |
| 72 | + public function executeSql(sql:String):tink.core.Promise<tink.core.Noise> { |
| 73 | + final cnx = getNativeConnection(); |
| 74 | + return new CockroachDbConnection(info, cnx, true).executeSql(sql); |
| 75 | + } |
| 76 | + |
| 77 | + public function isolate():Pair<Connection<Db>, CallbackLink> { |
| 78 | + final cnx = getNativeConnection(); |
| 79 | + return new Pair( |
| 80 | + (new CockroachDbConnection(info, cnx, false):Connection<Db>), |
| 81 | + (() -> cnx.handle(o -> switch o { |
| 82 | + case Success(native): native.release(); |
| 83 | + case Failure(_): // nothing to do |
| 84 | + }):CallbackLink) |
| 85 | + ); |
| 86 | + } |
| 87 | + |
| 88 | + function getNativeConnection() { |
| 89 | + return new Promise((resolve, reject) -> { |
| 90 | + var cancelled = false; |
| 91 | + pool.connect().then( |
| 92 | + client -> { |
| 93 | + if(cancelled) |
| 94 | + client.release(); |
| 95 | + else |
| 96 | + resolve(client); |
| 97 | + }, |
| 98 | + err -> reject(Error.ofJsError(err)) |
| 99 | + ); |
| 100 | + () -> cancelled = true; // there is no mechanism to undo connect, so we set a flag and release the client as soon as it is obtained |
| 101 | + }); |
| 102 | + } |
| 103 | +} |
| 104 | + |
| 105 | +class CockroachDbConnection<Db> implements Connection<Db> implements Sanitizer { |
| 106 | + final client:Promise<Client>; |
| 107 | + final info:DatabaseInfo; |
| 108 | + final formatter:CockroachDbFormatter; |
| 109 | + final parser:PostgreSqlResultParser<Db>; |
| 110 | + final streamBatch:Int = 50; |
| 111 | + final autoRelease:Bool; |
| 112 | + |
| 113 | + public function new(info, client, autoRelease) { |
| 114 | + this.info = info; |
| 115 | + this.client = client; |
| 116 | + this.formatter = new CockroachDbFormatter(); |
| 117 | + this.parser = new PostgreSqlResultParser(); |
| 118 | + this.autoRelease = autoRelease; |
| 119 | + } |
| 120 | + |
| 121 | + public function value(v:Any):String { |
| 122 | + if (Int64.isInt64(v)) |
| 123 | + return Int64.toStr(v); |
| 124 | + if (Std.is(v, Date)) |
| 125 | + return '(${(v : Date).getTime() / 1000})::timestamp'; |
| 126 | + if (Std.is(v, String)) |
| 127 | + return Client.escapeLiteral(v); |
| 128 | + if (Std.is(v, Bytes)) |
| 129 | + return "'\\x" + (cast v:Bytes).toHex() + "'"; |
| 130 | + |
| 131 | + return v; |
| 132 | + } |
| 133 | + |
| 134 | + public function ident(s:String):String |
| 135 | + return Client.escapeIdentifier(s); |
| 136 | + |
| 137 | + public function getFormatter() |
| 138 | + return formatter; |
| 139 | + |
| 140 | + function toError<A>(error:JsError):Outcome<A, Error> |
| 141 | + return Failure(Error.withData(error.message, error)); |
| 142 | + |
| 143 | + public function execute<Result>(query:Query<Db,Result>):Result { |
| 144 | + inline function fetch() return run(queryOptions(query)); |
| 145 | + return switch query { |
| 146 | + case Select(_) | Union(_): |
| 147 | + final parse:DynamicAccess<Any>->{} = parser.queryParser(query, formatter.isNested(query)); |
| 148 | + stream(queryOptions(query)).map(parse); |
| 149 | + case Insert(_): |
| 150 | + fetch().next(res -> res.rows.length > 0 ? Promise.resolve(new Id(res.rows[0][0])) : (Promise.NOISE:Promise<Dynamic>)); |
| 151 | + case Update(_): |
| 152 | + fetch().next(res -> {rowsAffected: res.rowCount}); |
| 153 | + case Delete(_): |
| 154 | + fetch().next(res -> {rowsAffected: res.rowCount}); |
| 155 | + case Transaction(_) | CreateTable(_, _) | DropTable(_) | AlterTable(_, _) | TruncateTable(_): |
| 156 | + fetch().next(r -> Noise); |
| 157 | + case _: |
| 158 | + throw query.getName() + " has not been implemented"; |
| 159 | + } |
| 160 | + } |
| 161 | + |
| 162 | + function queryOptions(query:Query<Db, Dynamic>): QueryOptions { |
| 163 | + final sql = formatter.format(query).toString(this); |
| 164 | + #if sql_debug |
| 165 | + trace(sql); |
| 166 | + #end |
| 167 | + return switch query { |
| 168 | + case Insert(_): |
| 169 | + {text: sql, rowMode: "array"}; |
| 170 | + default: |
| 171 | + {text: sql}; |
| 172 | + } |
| 173 | + } |
| 174 | + |
| 175 | + |
| 176 | + function stream(options: QueryOptions):Stream<Any, Error> { |
| 177 | + // TODO: use the 'row' event for streaming |
| 178 | + return client.next( |
| 179 | + client -> client.query(options) |
| 180 | + .toPromise() |
| 181 | + // don't use `Stream.ofIterator`, which may cause a `RangeError: Maximum call stack size exceeded` for large results |
| 182 | + .next(r -> Stream.ofNodeStream(r.command, Readable.from(cast r.rows), {onEnd: autoRelease ? () -> client.release() : null})) |
| 183 | + ); |
| 184 | + } |
| 185 | + |
| 186 | + function run(options: QueryOptions):Promise<Result> |
| 187 | + return client.next( |
| 188 | + client -> client.query(options) |
| 189 | + .toPromise() |
| 190 | + .asFuture() |
| 191 | + .withSideEffect(_ -> if(autoRelease) client.release()) |
| 192 | + ); |
| 193 | + |
| 194 | + public function executeSql(sql:String):tink.core.Promise<tink.core.Noise> { |
| 195 | + return run({text: sql}); |
| 196 | + } |
| 197 | +} |
0 commit comments