{"id":24319544,"url":"https://github.com/ryym/tyql","last_synced_at":"2026-04-21T11:07:06.709Z","repository":{"id":57144738,"uuid":"188569003","full_name":"ryym/tyql","owner":"ryym","description":"[WIP]: Moderately type safe ORM for TypeScript","archived":false,"fork":false,"pushed_at":"2019-08-26T13:59:13.000Z","size":262,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-02-18T03:05:56.699Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ryym.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2019-05-25T13:22:32.000Z","updated_at":"2019-08-26T13:59:15.000Z","dependencies_parsed_at":"2022-09-05T22:52:13.606Z","dependency_job_id":null,"html_url":"https://github.com/ryym/tyql","commit_stats":null,"previous_names":[],"tags_count":2,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ryym%2Ftyql","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ryym%2Ftyql/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ryym%2Ftyql/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ryym%2Ftyql/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ryym","download_url":"https://codeload.github.com/ryym/tyql/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":242926162,"owners_count":20207753,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-01-17T15:33:41.843Z","updated_at":"2026-04-21T11:07:06.676Z","avatar_url":"https://github.com/ryym.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"🚧 Under development\n\n# Tyql - Safe, Lightweight ORM for TypeScript\n\n[![CircleCI](https://circleci.com/gh/ryym/tyql.svg?style=svg)](https://circleci.com/gh/ryym/tyql)\n\n\u003e NOTE: Currently this document is written in Japanese.\n\u003e I'll rewrite this in English later.  \n\u003e Also, this document is in work in progress as well as the library itself.\n\nTyql は柔軟でタイプセーフな DB アクセスを実現する ORM /クエリビルダーです。\nTyql を使えば、最小限の手間で relational database とのインタラクションを安全かつ効率的に記述する事ができます。\n\nTyql は TypeScript が可能にする極めて柔軟な型定義を活かして作られています。例えば以下のような機能が使われています:\n\n- [Mapped types](mapped-types) (\u003e= TypeScript 2.1)\n- [Conditional Types](conditional-types) (\u003e= TypeScript 2.8)\n- [Strongly typed parameter list ](typed-parameter-list) (\u003e= TypeScript 3.0)\n\nそのため、 Tyql は TypeScript 3.0 以降でのみ動作します。\n\n[mapped-types]: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html#mapped-types\n[conditional-types]: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#conditional-types\n[typed-parameter-list]: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-0.html#tuples-in-rest-parameters-and-spread-expressions\n\n## Features\n\n- Type safe query construction\n  - Flexible result mapping\n  - Column level \u0026 Relation level safety\n- Ability to define relations between models\n  - Easy join\n  - Easy relation fetching\n\n### Features Tyql does NOT provide\n\n- Database migration\n- Auto generation of models or tables\n\n### Why is type safety matter?\n\n- Fearless model refactoring\n- Query construction with compiler assistance\n\n## What it looks like\n\n```typescript\nimport {Users} from './user';\nimport {connection} from './connection';\n\nconst rows = await Users()\n  .innerJoin(Users.Posts)\n  // .innerJoin(Users.Credentials)\n  .where(\n    Users.email.like('%example.com'),\n    Users.Posts.isDraft.eq(false),\n    // This does NOT compile because you do not join with the credentials table.\n    // Users.Credentials.token.isNotNull(),\n  )\n  .orderBy(Users.createdAt.desc())\n  .load(connection);\n\n// Result types are inferred automatically.\nrows.forEach(([user, post], i) =\u003e {\n  console.log(`row ${i}`, user, post);\n});\n```\n\n## Explore\n\nTyql による DB アクセスを、サンプルモデルとともに見てみましょう。\n\n### Sample models\n\n例として DB のテーブルに紐づく以下のモデルを考えます:\n\n```typescript\n// This corresponds with the \"users\" table.\nclass User {\n  constructor(\n    public readonly id: number,\n    public userName: string,\n    public email: string,\n    public createdAt: Date = new Date(),\n  ) {}\n}\n\n// This corresponds with the \"posts\" table.\n// \"users\" has-many \"posts\".\nclass Post {\n  constructor(\n    public readonly id: number,\n    public authorId: number, // foreign key for users.id\n    public title: string,\n    public content: string,\n    public createdAt: Date = new Date(),\n  ) {}\n}\n```\n\n#### Query builders\n\nこれらのモデルに、リレーション定義などのメタ情報を追加する事で各モデルに対応するクエリビルダーを生成できます (後述)。\n\n```typescript\nimport {table} from 'tyql';\nimport {User, Post} from './models';\nimport {conn} from './connection';\n\n// Query builders.\nconst Users = table(User, /* some meta data */);\nconst Posts = table(Post, /* some meta data */);\n\nasync () =\u003e {\n  const allUsers = await Users().orderBy(Users.email.asc()).load(conn);\n  console.log('emails:', allUsers.map(u =\u003e u.email));\n\n  const firstPost = await Posts().first(conn);\n  console.log('post:', firstPost);\n}\n```\n\n###  Flexible result mapping\n\nTyql で記述したクエリからは、結果をモデルとして取得する事も、個別に値を得る事も可能です。結果の型は全て推論されるため、明示的に型を指定する必要はありません。\n\n```typescript\n// Inferred as 'User[]'\nconst users = await Users().load(conn);\n\n// Inferred as '[User, Post][]'\nconst userAndPosts = await Users().innerJoin(Users.posts).load(conn);\nconst [user, post] = userAndPosts[0];\n\n// Inferred as '[number, string, Post][]'\nconst results = await Users()\n  .innerJoin(Users.posts)\n  .select(Users.id, Users.email, Users.posts())\n  .load(conn);\nconst [id, email, post] = results[0];\n```\n\n### Column level type safety\n\nクエリビルダーを用いてクエリを記述すれば、カラム名の typo や型の不一致といった trivial なミスをコンパイル時に検出できます。\n\n```typescript\n// ERROR: Property 'idd' does not exist\nUsers().where(Users.idd.eq(5)).first(conn);\n\n// ERROR: Argument of type '10' is not assignable\nUsers().where(Users.email.eq(10)).first(conn);\n```\n\n### Relation level type safety\n\nクエリビルダーは更に、無効なリレーションの使用をコンパイル時に検出できます。例えば以下のクエリはコンパイルが通りますが、\n\n```typescript\nUsers()\n  .innerJoin(Users.posts)\n  .where(Users.posts.title.like('WIP%'))\n  .load(conn);\n```\n\n以下はコンパイルエラーになります。JOIN していないリレーションのカラムをクエリ内で使っているからです。\n\n```typescript\n// COMPILE ERROR\nUsers()\n  // .innerJoin(Users.posts)\n  .where(Users.posts.title.like('WIP%'))\n  .load(conn);\n```\n\n### Easy Relation Loading\n\nTyql は一般的な ORM とは異なり、リレーションをモデルのプロパティとして持たせる事はしません。\n\n```typescript\nclass User {\n  // A model does not have a relation property like this:\n  // posts: Post[];\n}\n```\n\nこれはライブラリの機能をシンプルにし、挙動を予測可能にするための意図的な選択です (詳細は後述)。\nそのため、 ActiveRecord などの ORM にあるような eager loading / lazy loading 機能もありません。\n代わりに、関連を簡単に取得するためのユーティリティが用意されています。\n\n```typescript\n// If you want to load some relations from these users,\nconst users = await Users().load(conn);\n\n// You can load them as 'Map\u003ckey, Model[]\u003e' by 'rels' method.\nconst [postsByAuthor /*, ...other results */] = await Users()\n  .rels(Users.posts /*, ...other relations */)\n  .loadMaps(users, conn);\n\nusers.forEach(user =\u003e {\n  const posts = postsByAuthor.get(user.id);\n  console.log(user, posts);\n});\n```\n\n## How to create Query Builders\n\n前節までで見たように、 Tyql のクエリビルダーを使うと安全にクエリを構築する事ができます。\nクエリビルダーは、モデルといくつかの付加情報、そしてリレーションの定義をする事で生成できます。\n正直に言えば、ここが Tyql を使う上で一番面倒な部分です。しかしあなたがコード量の少なさよりも明示性と安全さを重視するなら、払う価値のある手間になるはずです。\n\n先にコードを見てみましょう。以下は `User` モデルに対応する `Users` クエリビルダーを定義する例です。 `Explore` セクションでは省略しましたが、 `User` モデル自体に付加情報を持たせます。\n\n```typescript\nimport {table, to} from 'tyql';\nimport {Post} from './models/posts';\n\nexport class User {\n  constructor(\n    public readonly id: number,\n    public userName: string,\n    public email: string,\n    public createdAt: Date = new Date(),\n  ) {}\n\n  // First, you need to define a special static property 'tyql'.\n  static tyql = {\n    table: 'users',\n    template: () =\u003e new User(0, '', '', new Date()),\n  }\n}\n\n// Next, define the Users query builder with its relations.\nexport const Users = table(User, {\n  posts: to(Post, 'authorId', 'id'),\n});\n\n// That's it.\n```\n\nまずモデルクラスの `tyql` プロパティで以下の2つを定義します:\n\n- テーブル名\n- モデルの雛形を返す `template` 関数\n\nTyql がクエリの結果をモデルにマッピングする際には、この `template` 関数を使ってレコードの雛形を作り、そこに実際の値をセットしていきます。\n\nしかし、なぜ `template` のような関数が必要なのでしょうか？\nもっとエレガントな方法は無いのでしょうか？  \n実際これは暫定的な方法であり、我々もこれがベストだとは考えていません。しかし JS/TS という環境で型安全な ORM を作るには、このような方法しかまだ見つけられていない状況です。\n詳細は `Why is template function necessary?` セクションに記していますが、もしより良い方法があればぜひ教えていただきたいです。\n\n### Relation Definition\n\nさて、面倒な `template` の定義さえ終われば後は簡単です。リレーションの定義を渡してモデルごとのクエリビルダーを生成しましょう。\n\n```typescript\nexport const Users = table(User, {\n  posts: to(Post, 'authorId', 'id'),\n});\n\nexport const Posts = table(Post, {\n  author: to(User, 'id', 'authorId'),\n});\n\n// Then you can write queries as you like.\nUsers().where(Users.email.isNull());\nPosts().innerJoin(Posts.author).select(Posts.author(), Posts.title);\n```\n\n各リレーションの定義には以下の3つが必要です:\n\n- 結合先のテーブルに対応するモデルクラス\n    - 注意: テーブルのクエリビルダーではありません (use `User`, not `Users`)\n- 結合先テーブルのカラム名\n- 結合元テーブルのカラム名\n\n(正確にはカラム名ではなく、対応するモデルのプロパティ名を使います)\n\nこれらをこの順序で `to` 関数に渡せば完了です。\n\n```typescript\nconst relations = {\n  posts: to(Post, 'authorId', 'id'),\n};\n```\n\nプロパティ名は文字列で指定していますが、存在しないプロパティ名を指定するとコンパイルエラーになるので安全です。\n\nまた現時点では結合に使うプロパティ名を必ず指定する必要があります。その代り、カラム名に命名規約はありません。\n\n## Policy on handling relations\n\n前述したように、 Tyql ではモデル間のリレーションをプロパティとしては表現しません。そのため、 ActiveRecord などの ORM が提供してくれるような eager loading / lazy loading は存在しません。\n\n以下は ActiveRecord と Tyql でリレーションを取得するコードの比較です:  \n(`users` が `posts` に加えて `comments` というリレーションを持つとします)\n\n```ruby\n# ActiveRecord\nusers = User.includes(:posts, :comments)\nusers.each do |user|\n  p [user.id, user.posts, user.comments]\nend\n```\n\n```typescript\n// Tyql\nconst users = await Users().load(conn);\nconst [posts, comments] = await Users()\n  .rels(Users.posts, Users.comments)\n  .loadMaps(users, conn);\n\nusers.forEach(user =\u003e {\n  console.log(user.id, posts.get(user.id), comments.get(user.id));\n});\n```\n\nどちらも全ユーザと、各ユーザが持つ全 `posts` と `comments` を取得しています。\n残念ながら、ActiveRecord に比べると Tyql のコード量は多めです。\nしかし、後者には以下のメリットがあります:\n\n- クエリの走るタイミングが明確である。\n- 自動でクエリが走らないので N+1 クエリ問題が起きない。\n\nActiveRecord の簡潔なインターフェイスは確かに非常に強力ではあるものの、効率的に使うためにはその裏側でどのようなクエリが走るのかを理解する必要があります。\n例えばもし上記のコードで `comments` を `includes` 忘れても、コードは動作します:\n\n```ruby\n# ActiveRecord\nusers = User.includes(:posts) # :comments\nusers.each do |user|\n  p [user.id, user.posts, user.comments]\nend\n```\n\nこれは `user.comments` が呼ばれるタイミングでそのユーザのコメント一覧を取得しているからです。しかしこれではユーザの数だけコメント一覧を取得するクエリが走ってしまい、非常に無駄です。\nこれがいわゆる N+1 クエリ問題ですが、 eager loading / lazy loading のない Tyql ではそもそもこの問題は起きようがありません。\n\nこのようにリッチな ORM では得てして、簡潔なコードの裏側でどんな風に DB アクセスがなされるのかを知る必要があります。 ActiveRecord でいえば `includes` や `joins`, `eager_load` などの似て非なるメソッドを状況に応じて使い分けるスキルが必要になるでしょう。\n\n一方 Tyql では JOIN して一度にデータを取得するか、リレーションの定義を基に複数回のクエリに分けて取得するかの二択であり、その選択はコードとしてそのまま表現されます。\nDB アクセスへの理解が必要になるのは変わりませんが、インターフェイスが暗に内部の理解を迫る事はありません。\n\nまたモデル自体がリレーションを持たない設計は、モデル同士をより疎結合にします。\nモデル同士が独立しているので、クエリの結果として得られたリレーションをモデルのプロパティに落とし込む処理はありません。そのためテーブル形式で得られるクエリの結果が、オブジェクトのツリーへとどのようにマッピングされるのかを想像する必要もありません。\n\nActiveRecord に限らず、効率的な DB アクセスを意識するなら、どんな ORM を使っても SQL や DB の知識は必要になると思います。そういう意味で、 ORM は DB アクセスを隠蔽する抽象化手段というよりは、ある種のシンタックスシュガーとして捉えるのが良いかもしれません。\nつまりはクエリの構築や結果のマッピングをその言語にふさわしいコードに落とし込むためのツールであり、それ以上のものではない、といった位置づけです。\nTyql もこの思想に基づいており、あくまで DB へのアクセスを型安全に記述するためのライブラリです。 DB アクセス自体を抽象・隠蔽したければ、あなたのアプリケーションに合う設計をあなた自身で行う必要があるでしょう。 Tyql はその手助けをしてくれます。\n\n## Why is `template` function necessary?\n\nクエリビルダーの生成において `template` 関数の定義が必須なのは完全に技術的な制約ゆえであり、何らライブラリデザインとしての意図はありません。\n可能であるなら無くても済むようにしたいのですが、現状ではより良い方法が見つかっていません。\n\nというのも、 Tyql が掲げる型安全なクエリの構築を実現するためには、対象となるテーブルのカラム一覧、つまりは対応するモデルのプロパティ一覧が必要になります。重要なのは、このカラム一覧の情報がコンパイル時と実行時の両方で必要になる点です。\n\n```typescript\nimport {table} from 'tyql';\n\nclass User {\n  id: number;\n  name: string;\n}\n\n// Tyql extracts property data from a model class.\nconst Users = table(User);\n\n// The extracted property data must be statically typed.\n// And of course it must function in runtime.\nconsole.log(Users.id, Users.name);\n```\n\nコンパイル時にプロパティ情報を取得するのは簡単で、モデルとなるクラスの定義さえあれば TypeScript の Mapped Types などを使って実現できます。\n\n```typescript\nclass User {\n  id: number;\n  name: string;\n}\n\ntype Columns\u003cT\u003e = {\n  [P in keyof T]: Column\u003cT[P]\u003e;\n}\n\ntype Users = Columns\u003cUser\u003e;\n// Users: { id: Column\u003cnumber\u003e, name: Column\u003cstring\u003e };\n```\n\nしかし、 TypeScript はあくまで JavaScript のスーパーセットであり、コンパイル後はただの JavaScript になります。そのため、コンパイル時にあるようなクラスのプロパティ情報を実行時に取得する事は通常できません。\n\n```javascript\n// The User class defined above compiles into a function such as:\nvar User = /** @class */ (function () {\n    function User() {\n    }\n    return User;\n}());\n// No property information remains.\n```\n\nつまり、クラス定義だけではコンパイル時にしかプロパティ情報にアクセスできません。\n\nしかし実際に値がセットされたインスタンスがあれば、実行時にもプロパティ情報を得る事ができます。\n\n```javascript\nconst user = User.tyql.template();\nObject.keys(users); //=\u003e [\"id\", \"name\"]\n```\n\nこれが `template` 関数が必要となる理由です。実行時には、この関数が作るインスタンスからプロパティ情報を得ています。\n\n### How about Decorators?\n\n実は 実行時に一部の型情報を得る方法も (自分の知る限りでは) 1つだけ存在します。それが Decorator という experimental な機能です。\nこれをクラスの各プロパティに指定すると、実行時にプロパティ情報にアクセスすることができます。\n\n```typescript\nclass User {\n  @column\n  id: number;\n\n  @column\n  name: string;\n}\n// Actually a decorator is just a function and\n// the `column` function is called for each property at runtime.\n```\n\nそのため、この Decorator を使用すれば `template` 関数が不要になりそうです。しかし、この案は採用しませんでした。\nというのも、例えばもし特定のプロパティに decorator を付与し忘れたらどうなるでしょう？\n\n```typescript\nclass User {\n  @column\n  id: number;\n\n  @column\n  name: string;\n\n  // Oops\n  birthday: Date;\n}\n```\n\nすると実行時に `@column` は `birthday` の存在を知ることができないため、 `User` のカラムは `id`, `name` のみと判断されます。\nところが、 `User` クラスを基に生成されるクエリビルダーは `id`, `name`, `birthday` の3つを全てカラムとして認識します。\n\n```typescript\ntype Users = Columns\u003cUser\u003e;\n// Users: { id: Column\u003cnumber\u003e, name: Column\u003cstring\u003e, birthday: Column\u003cDate\u003e };\n```\n\nすると実行時には存在しない `birthday` というカラムが、コンパイル時には存在する事になってしまいます。\nこれは、コンパイルは通るのに実行時に予期せぬエラーが起きるという、面倒なバグを生むでしょう。\n\nつまり Decorator を使うにあたり問題なのは、「どのプロパティに decorator が付与されているか」は実行時にしかわからない点です。 Decorator の情報をコンパイル時にも使えるならこの方法が良さそうなのですが、現時点では (自分が知る限りだと) 出来ません。\n\nよって、モデルクラスのプロパティ情報をコンパイル時と実行時の両方でズレなく得るためのシンプルな方法として、全てのプロパティを持ったインスタンスを返す `template` 関数を定義してもらう形にしました。\n\n逆に言うと、 Tyql ではモデルクラスの (メソッドと private プロパティを除く) 全てのプロパティがカラムに対応している必要があります。特定のプロパティをマッピングの対象外とする事は現状できません。\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fryym%2Ftyql","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fryym%2Ftyql","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fryym%2Ftyql/lists"}