griffiths-waite/kysely-oracledb
Tentang
Kysely Dialect and Type Generator for Oracle DB.
Data dan analisisPertumbuhan bintang terukur
- dalam 24 jam
- 0
- dalam 7 hari
- 0
- dalam 15 hari
- 0
- dalam 1 bulan
- 0
Perubahan bersih pada periode yang tumpang tindih, bukan total harian. Pengukuran yang belum tersedia dibiarkan kosong. Bintang menunjukkan perhatian, bukan kualitas.
README.md
Aslikysely-oracledb
Kysely Dialect and Type Generator for Oracle DB.
Installation
npm install kysely oracle-db kysely-oracledb
Dialect Usage
Create a dialect with a connection pool, then pass it to the Kysely instance:
import type { DB } from "./types.js";
import oracledb from "oracledb";
import { Kysely, type Generated } from "kysely";
import { OracleDialect } from "kysely-oracledb";
const pool = await oracledb.createPool({
user: "username",
password: "password",
connectionString: "localhost:1521/FREEPDB1",
});
const dialect = new OracleDialect({
pool,
});
const db = new kysely<DB>({ dialect });
You can now use Kysely to query your database:
import { db } from "./database.js";
const items = await db
.from("ITEMS")
.select("ID", "NAME")
.where("AMOUNT", ">", 10)
.execute();
console.log(items);
Read the type generation section for information on generating types.
Dialect Configuration
log
Enables logging, in the same way as Kysely's log option. The levels are:
query: a query completeserror: a query, commit, rollback or connection close failsconnection: a connection is acquired or releasedtransaction: a transaction begins, commits or rolls back, or a savepoint is created or rolled back to
// Log the given levels to the console
log: ["query", "error"],
// Send every level to your own function
log: (event) => logger.debug(event),
// Send the given levels to your own function
log: { levels: ["query", "error"], logger: (event) => logger.info(formatLogEvent(event)) },
formatLogEvent returns the message the console logger would print. Query events hold the SQL and its parameters separately, so parameter values aren't written into the logs.
Kysely's own log option also logs queries and errors, so turning on query or error in both places logs each query twice.
executeOptions
Global execute options to pass to every Kysely query.
For example, to commit transactions without needing to wrap each query in a db.transaction(), you can pass the autoCommit option to the dialect:
import oracledb from "oracledb";
import { OracleDialect } from "kysely-oracledb";
const pool = await oracledb.createPool({
user: "username",
password: "password",
connectionString: "localhost:1521/FREEPDB1",
});
const dialect = new OracleDialect({
pool,
executeOptions: {
autoCommit: true,
},
});
compilerOptions
Kysely compiler options. Currently the only option available is useNonQuotedIdentifiers which controls how the compiled SQL represents the names of objects. Queries use quoted identifiers by default.
introspectorOptions
Kysely allows you to extract table, view, and schema metadata using the Introspector class. The Oracle dialect accepts additional introspection options to filter this metadata.
Extending Kysely
Kysely doesn't support Oracle specific syntax. In these scenarios, you can extend Kysely using the sql template tag.
For example, to round a number column:
import { db } from "./database.js";
import type { Expression } from "kysely";
const round = (number: Expression<number>, decimals: number) =>
sql<number>`round(${number},${decimals})`;
const items = await db
.from("ITEMS")
.select("ID", round("AMOUNT", 1).as("AMOUNT"))
.execute();
Bind objects in the sql template tag are passed to node-oracledb unchanged, so you can use out binds, e.g. to call a procedure. The values are returned in outBinds, in bind order:
const result = (await sql`
begin
GET_ITEM_COUNT(${"A"}, ${{ dir: oracledb.BIND_OUT, type: oracledb.NUMBER }});
end;
`.execute(db)) as OracleQueryResult<unknown, [number]>;
const count = result.outBinds?.[0];
To return values from an insert, update or delete, use withReturning instead.
Read the official documentation for more information on extending Kysely.
Type Generation
To get the most out of Kysely, you need to define types for your database schema. You can define these manually or you can generate them using the generate function.
import oracledb from "oracledb";
import { generate } from "kysely-oracledb";
const pool = await oracledb.createPool({
user: "username",
password: "password",
connectionString: "localhost:1521/FREEPDB1",
});
await generate({
pool,
introspectorOptions: {
type: "tables",
tables: ["ITEMS"],
},
});
This will generate a types file with the following structure:
// This file was generated automatically. Please don't edit it manually!
// kysely-oracledb:8214f7e2928d5c6f
import type { Generated, Insertable, Selectable, Updateable } from "kysely";
interface ItemsTable {
ID: Generated<number>;
NAME: string;
AMOUNT: number;
}
export type Items = Selectable<ItemsTable>;
export type NewItems = Insertable<ItemsTable>;
export type ItemsUpdate = Updateable<ItemsTable>;
export interface DB {
ITEMS: ItemsTable;
}
Type Mapping
| Oracle type | TypeScript |
|---|---|
VARCHAR2, NVARCHAR2, CHAR, NCHAR, LONG, ROWID, UROWID, XMLTYPE, ClOB, NCLOB |
string |
NUMBER, FLOAT, BINARY_FLOAT, BINARY_DOUBLE |
number |
BOOLEAN |
boolean |
DATE, TIMESTAMP, TIMESTAMP WITH TIME ZONE, TIMESTAMP WITH LOCAL TIME ZONE |
Date |
RAW, LONG RAW, BLOB |
Buffer |
VECTOR |
Float32Array | Float64Array | Int8Array | Uint8Array |
INTERVAL YEAR TO MONTH |
IntervalYM |
INTERVAL DAY TO SECOND |
IntervalDS |
JSON, BFILE |
unknown |
By default node-oracledb returns LOB columns as Lob streams. To receive the types above, configure the driver:
oracledb.fetchAsString = [oracledb.CLOB, oracledb.NCLOB];
oracledb.fetchAsBuffer = [oracledb.BLOB];
Change Detection
The generated types file contains a unique fingerprint kysely-oracledb:<fingerprint>. Subsequent type generation runs compare fingerprints to determine if there are any changes.
Manual file edits are not detected when comparing changes, therefore the types should not be modified once generated.
The changed flag to indicates if there are any changes to the types. Metadata is always updated regardless of whether the types file is updated or not, and the metadataChanged flag indicates if there are any changes to the metadata.
CLI
The generator can also be run from the command line without writing a script:
npx kysely-oracledb generate --user username --connect-string localhost:1521/FREEPDB1 --type tables
Connection options can be passed as flags or environment variables. Flags take priority over environment variables.
Use --env-file to load the environment variables from a file. Variables already set in the environment take priority over the file.
{
"scripts": {
"db:types": "kysely-oracledb generate --env-file .env -o src/db/types.ts"
}
}
| Flag | Environment variable | Description |
|---|---|---|
--user |
ORACLE_USER |
Database user. |
--password |
ORACLE_PASSWORD |
Database password. |
--connect-string |
ORACLE_CONNECT_STRING |
Connect string, e.g. localhost:1521/FREEPDB1. |
--env-file |
Load environment variables from a file. | |
--thick |
Enable node-oracledb thick mode. | |
--lib-dir |
Oracle Client library directory. Implies --thick. |
|
--type |
Filter by object type, tables or views. |
|
--schemas |
Filter by schema name. Comma-separated or repeated. | |
--tables |
Filter by table or view name. Comma-separated or repeated. | |
-o, --out |
Types file path. Default: types.ts. |
|
--metadata |
Output the table metadata. | |
--metadata-out |
Metadata file path. Default: tables.json. Implies --metadata. |
|
--camel-case |
Use camelCase for generated types. | |
--underscore-before-digits |
CamelCasePlugin option used to detect unsafe columns. |
|
--underscore-between-uppercase-letters |
CamelCasePlugin option used to detect unsafe columns. |
|
--check |
Check if the generated files are out of date without writing them. | |
--quiet |
Only output warnings and errors. |
Use --check in CI to verify that the committed types match the database. The CLI exits with code 1 if the files are out of date, or code 2 for any other error.
npx kysely-oracledb generate --env-file .env -o src/db/types.ts --check
Generator Configuration
The generator can be configured with the same options as the dialect, plus the following additional options:
camelCase
Convert database table names and column names to camel case.
Default: false.
camelCaseOptions
The same options used for the CamelCasePlugin. These options are used to detect columns whose camelized name can't be converted back safely.
For example, ISO_2CHAR_CODE is camelized to iso2charCode, but converts back to ISO2CHAR_CODE when underscoreBeforeDigits is disabled. If your schema also contains table columns with trailing digits then this creates a scenario where some columns can't be safely converted.
await generate({
pool,
camelCase: true,
camelCaseOptions: { underscoreBeforeDigits: false },
});
// Output: Unsafe columns detected with the current camelCase options: ISO_2CHAR_CODE (iso2charCode)
See CamelCaseOverridesPlugin for handling unsafe columns at runtime.
metadata
Output the table metadata to a file.
Default: false.
filePath
File path to write the types to. Can be an absolute path, or relative to the current working directory. missing directories are created.
await generate({ pool, filePath: "./src/db/types.ts" });
Default: types.ts.
metadataFilePath
File path to write the metadata to. Can be an absolute path, or relative to the current working directory. missing directories are created.
await generate({
pool,
metadata: true,
metadataFilePath: "./src/metadata/tables.json",
});
Default: tables.json.
logger
Logger for generator messages, such as the result summary and unsafe column warnings. It needs info and warn methods, so the console and most logging libraries work as is.
await generate({ pool, logger: { info: () => {}, warn: console.warn } });
Default: console.
write
Write the generated files. When disabled, files are only compared and the changed and metadataChanged flags indicate if they are out of date.
const { changed } = await generate({ pool, write: false });
Default: true.
Plugins
WithExecuteOptions
This plugin allows you to modify the executeOptions for a specific query. This takes priority over global execute options set in the dialect.
import { withExecuteOptions } from "kysely-oracledb";
await db
.insertInto("ITEMS")
.values({ NAME: "New item", amount: 9.99 })
.withPlugin(withExecuteOptions({ autoCommit: true }))
.execute();
WithReturning
Oracle returns values from an insert, update or delete with returning ... into out binds, and each out bind needs a type. withReturning sets the type of each column passed to returning, and the rows are returned as normal. Pass it to $call after returning.
import oracledb from "oracledb";
import { withReturning } from "kysely-oracledb";
const item = await db
.insertInto("ITEMS")
.values({ NAME: "New item" })
.returning(["ID", "NAME", "CREATED_AT"])
.$call(
withReturning({
ID: oracledb.NUMBER,
NAME: { type: oracledb.STRING, maxSize: 255 },
CREATED_AT: oracledb.DATE,
}),
)
.executeTakeFirstOrThrow();
// insert into "ITEMS" ("NAME") values (:1) returning "ID", "NAME", "CREATED_AT" into :2, :3, :4
- The keys are the keys of the returned row, including aliases. Every returned column needs a type, and missing or extra keys are type errors.
- With
CamelCasePlugin, use the camelCase keys, e.g.createdAtforCREATED_AT. - Expressions need an alias, e.g.
sql<string>`lower(NAME)`.as("lowerName"). - Strings bound as
oracledb.STRINGare limited to 4000 bytes. Bind larger values asoracledb.CLOBororacledb.BLOB. These are returned as a string orBufferwhenoracledb.fetchAsStringororacledb.fetchAsBufferinclude their type, the same as a query. Otherwise they're returned as aLob. - An update or delete returns a row for every affected row.
- Oracle doesn't support
returningwithreturningAll(), multi-row inserts,insert ... selectormerge. These throw an error.
CamelCaseOverridesPlugin
An extension to the CamelCasePlugin that accepts overrides for columns who's camelized name can't be converted back safely.
import { CamelCaseOverridesPlugin } from "kysely-oracledb";
const db = new Kysely<DB>({
dialect: new OracleDialect({ pool }),
plugins: [
new CamelCaseOverridesPlugin(
{ iso2charCode: "ISO_2CHAR_CODE" },
{ upperCase: true },
),
],
});
Each override maps the affected camelized property name to its real column (or table) name.
Contributing
Contributions are welcome! Please open an issue or a pull request on GitHub.
Jelajahi proyek terkait
Memuat…