markdown-sql 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +421 -2
- package/dist/core-BGXPYnlj.d.cts +143 -0
- package/dist/core-BGXPYnlj.d.ts +143 -0
- package/dist/drizzle.cjs +1034 -0
- package/dist/drizzle.cjs.map +1 -0
- package/dist/drizzle.d.cts +39 -0
- package/dist/drizzle.d.ts +39 -0
- package/dist/drizzle.js +1028 -0
- package/dist/drizzle.js.map +1 -0
- package/dist/engine-rSx4jmMV.d.cts +7 -0
- package/dist/engine-rSx4jmMV.d.ts +7 -0
- package/dist/index.cjs +1101 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +86 -0
- package/dist/index.d.ts +86 -0
- package/dist/index.js +1095 -0
- package/dist/index.js.map +1 -0
- package/dist/pg.cjs +1289 -0
- package/dist/pg.cjs.map +1 -0
- package/dist/pg.d.cts +79 -0
- package/dist/pg.d.ts +79 -0
- package/dist/pg.js +1279 -0
- package/dist/pg.js.map +1 -0
- package/dist/schema-B1HlomD9.d.cts +16 -0
- package/dist/schema-D3mwSEnX.d.ts +16 -0
- package/package.json +116 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
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.
|
package/README.md
CHANGED
|
@@ -1,3 +1,422 @@
|
|
|
1
|
-
#
|
|
1
|
+
# MarkdownSQL
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Query folders of markdown files with SQL. Each folder is a table, each `.md` file is a row, YAML frontmatter holds the columns, the file name is the key and the markdown body is one more column.
|
|
4
|
+
|
|
5
|
+
MarkdownSQL reads the files into an in-memory SQLite database and gives you read-only SQL over it: no ORM, no schema file, no build step. An optional file watcher keeps the index in sync while you edit.
|
|
6
|
+
|
|
7
|
+
- **Zero config:** every sub-folder is a table and its columns are inferred from the frontmatter, or declare them with a few type names.
|
|
8
|
+
- Full SQLite `SELECT`: joins across folders, aggregates, window functions and `json_each` over YAML lists.
|
|
9
|
+
- File watcher with checksums and debouncing, so only changed files are re-read.
|
|
10
|
+
- Optional [Drizzle ORM](https://orm.drizzle.team) adapters: `markdown-sql/drizzle` (SQLite) and `markdown-sql/pg` ([PGlite](https://pglite.dev), Postgres in WebAssembly, with arrays, `jsonb`, extensions, indexes and live queries).
|
|
11
|
+
- No framework dependency. The main entry point never loads Drizzle or PGlite.
|
|
12
|
+
|
|
13
|
+
> **Status:** version 1 is read-only. Writes and file migrations are on the [roadmap](#roadmap). MarkdownSQL was published as `drizzle-md` before; see [Migrating from drizzle-md](#migrating-from-drizzle-md).
|
|
14
|
+
|
|
15
|
+
## Install
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
npm install markdown-sql
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Node.js 22 or later. The default SQLite driver is [better-sqlite3](https://github.com/WiseLibs/better-sqlite3), which installs a prebuilt binary. Node's built-in `node:sqlite` works too (`driver: 'node:sqlite'`, Node.js 22.16 or later). `drizzle-orm` and PGlite are optional peer dependencies, needed only for `markdown-sql/drizzle` and `markdown-sql/pg`.
|
|
22
|
+
|
|
23
|
+
## Quick start
|
|
24
|
+
|
|
25
|
+
```text
|
|
26
|
+
content/
|
|
27
|
+
├── authors/
|
|
28
|
+
│ ├── ada.md
|
|
29
|
+
│ └── grace.md
|
|
30
|
+
└── posts/
|
|
31
|
+
├── hello-world.md
|
|
32
|
+
└── second-post.md
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
`content/posts/hello-world.md`:
|
|
36
|
+
|
|
37
|
+
```markdown
|
|
38
|
+
---
|
|
39
|
+
title: Hello, world
|
|
40
|
+
author: ada
|
|
41
|
+
published: 2026-11-01
|
|
42
|
+
views: 120
|
|
43
|
+
tags: [intro, sql]
|
|
44
|
+
---
|
|
45
|
+
|
|
46
|
+
# Hello
|
|
47
|
+
|
|
48
|
+
The first post.
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
```typescript
|
|
52
|
+
import { markdownSql } from 'markdown-sql';
|
|
53
|
+
|
|
54
|
+
const md = await markdownSql({ root: 'content' });
|
|
55
|
+
|
|
56
|
+
// Template values are bound as parameters, never pasted into the SQL.
|
|
57
|
+
const popular = await md.sql`
|
|
58
|
+
select p.title, a.name as author
|
|
59
|
+
from posts p join authors a on a.id = p.author
|
|
60
|
+
where p.views > ${100}
|
|
61
|
+
order by p.published desc`;
|
|
62
|
+
|
|
63
|
+
// Or a string with ? placeholders.
|
|
64
|
+
const tagged = await md.query(
|
|
65
|
+
'select p.id from posts p, json_each(p.tags) t where t.value = ?',
|
|
66
|
+
['sql'],
|
|
67
|
+
);
|
|
68
|
+
|
|
69
|
+
md.tables(); // [{ table: 'authors', dir: 'authors', columns: [...] }, { table: 'posts', ... }]
|
|
70
|
+
await md.close();
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
Rows are plain objects keyed by result column name, with SQLite values: text, numbers, `bigint`, `null` or bytes.
|
|
74
|
+
|
|
75
|
+
## Tables and columns
|
|
76
|
+
|
|
77
|
+
| File part | Column |
|
|
78
|
+
| --- | --- |
|
|
79
|
+
| Folder under `root` | A table with the folder's name. Folders starting with `.` or `_` are skipped. |
|
|
80
|
+
| File name without the extension | The key column, `id` (TEXT primary key). |
|
|
81
|
+
| Each frontmatter key | A column with the same name. |
|
|
82
|
+
| Markdown body | The `body` column. |
|
|
83
|
+
|
|
84
|
+
Frontmatter is parsed with the YAML 1.2 core schema. Without `columns`, each table's column types are inferred from all of its files on the first load:
|
|
85
|
+
|
|
86
|
+
| Values seen for a key | Column type | Stored as |
|
|
87
|
+
| --- | --- | --- |
|
|
88
|
+
| only `true` / `false` | `boolean` | INTEGER `1` / `0` |
|
|
89
|
+
| only whole numbers | `integer` | INTEGER |
|
|
90
|
+
| numbers, some with decimals | `real` | REAL |
|
|
91
|
+
| only strings (dates included), or mixed scalars | `text` | TEXT |
|
|
92
|
+
| any list or mapping | `json` | TEXT holding JSON, for SQLite's `json_*` functions |
|
|
93
|
+
| only `null` | `text` | TEXT |
|
|
94
|
+
|
|
95
|
+
Inferred columns are never required. Dates stay text exactly as written; declare a `date` column to normalize them.
|
|
96
|
+
|
|
97
|
+
Declare tables to pick the folders, rename the key or body column, or fix the column types:
|
|
98
|
+
|
|
99
|
+
```typescript
|
|
100
|
+
const md = await markdownSql({
|
|
101
|
+
root: 'content',
|
|
102
|
+
tables: {
|
|
103
|
+
articles: {
|
|
104
|
+
dir: 'posts', // folder under root, defaults to the table name
|
|
105
|
+
key: 'slug', // column for the file name, defaults to 'id'
|
|
106
|
+
body: 'content', // column for the body, defaults to 'body'; false skips it
|
|
107
|
+
columns: {
|
|
108
|
+
title: { type: 'text', required: true },
|
|
109
|
+
published: 'date', // ISO 8601 in frontmatter, stored as 2026-11-01T00:00:00.000Z
|
|
110
|
+
views: 'integer',
|
|
111
|
+
status: { type: 'text', values: ['idea', 'published'] },
|
|
112
|
+
tags: 'json',
|
|
113
|
+
},
|
|
114
|
+
},
|
|
115
|
+
},
|
|
116
|
+
});
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
With `tables`, only the listed tables are loaded; a table without `columns` still infers them. Declared columns are checked like the Drizzle ones: a value that doesn't fit (say `views: many`) or a missing required key makes the file invalid. Frontmatter keys that match no declared column are ignored and counted in `md.report()`.
|
|
120
|
+
|
|
121
|
+
| Member | Meaning |
|
|
122
|
+
| --- | --- |
|
|
123
|
+
| `query(sql, params?)` | Runs one read-only statement with `?` parameters; resolves to the rows. Booleans bind as `1` / `0`. |
|
|
124
|
+
| ``sql`…` `` | Tagged-template form of `query`. |
|
|
125
|
+
| `tables()` | Tables, folders and columns (name, type, role, required), including inferred ones. |
|
|
126
|
+
| `diagnostics()`, `report()`, `reload()`, `watch()`, `subscribe()`, `settled()`, `close()` | The shared index lifecycle, described below. |
|
|
127
|
+
|
|
128
|
+
## Drizzle ORM (`markdown-sql/drizzle`)
|
|
129
|
+
|
|
130
|
+
`markdown-sql/drizzle` gives you a normal, read-only Drizzle database over the same index, so you define tables with Drizzle's own `sqliteTable` and get typed `select`, `where`, joins, aggregates, raw SQL and relational queries (`db.query`).
|
|
131
|
+
|
|
132
|
+
```bash
|
|
133
|
+
npm install markdown-sql drizzle-orm
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
```typescript
|
|
137
|
+
import { eq, relations } from 'drizzle-orm';
|
|
138
|
+
import { integer, sqliteTable, text } from 'drizzle-orm/sqlite-core';
|
|
139
|
+
import { drizzleMd } from 'markdown-sql/drizzle';
|
|
140
|
+
|
|
141
|
+
export const authors = sqliteTable('authors', {
|
|
142
|
+
id: text().primaryKey(), // file name without .md
|
|
143
|
+
name: text().notNull(),
|
|
144
|
+
body: text().notNull(), // markdown body
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
export const posts = sqliteTable('posts', {
|
|
148
|
+
id: text().primaryKey(),
|
|
149
|
+
title: text().notNull(),
|
|
150
|
+
author: text().notNull(),
|
|
151
|
+
published: integer({ mode: 'timestamp' }).notNull(), // ISO date in frontmatter
|
|
152
|
+
draft: integer({ mode: 'boolean' }).notNull().default(false),
|
|
153
|
+
tags: text({ mode: 'json' }).$type<string[]>().notNull().$defaultFn(() => []),
|
|
154
|
+
body: text().notNull(),
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
export const postsRelations = relations(posts, ({ one }) => ({
|
|
158
|
+
writer: one(authors, { fields: [posts.author], references: [authors.id] }),
|
|
159
|
+
}));
|
|
160
|
+
|
|
161
|
+
const md = await drizzleMd({
|
|
162
|
+
root: 'content',
|
|
163
|
+
schema: { authors, posts, postsRelations },
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
// Plain Drizzle: posts joined with their authors.
|
|
167
|
+
const feed = await md.db
|
|
168
|
+
.select({ title: posts.title, author: authors.name, published: posts.published })
|
|
169
|
+
.from(posts)
|
|
170
|
+
.innerJoin(authors, eq(posts.author, authors.id))
|
|
171
|
+
.where(eq(posts.draft, false));
|
|
172
|
+
|
|
173
|
+
// Relational queries work too.
|
|
174
|
+
const post = await md.db.query.posts.findFirst({
|
|
175
|
+
where: eq(posts.id, 'hello-world'),
|
|
176
|
+
with: { writer: true },
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
await md.close();
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
### How files map to Drizzle columns
|
|
183
|
+
|
|
184
|
+
| File part | Column |
|
|
185
|
+
| --- | --- |
|
|
186
|
+
| File name without the extension | The key column, `id` by default. Integer keys are parsed from names like `1.md`. |
|
|
187
|
+
| Each frontmatter key | The column with the same **property name** in the Drizzle table (`author`, not the SQL name). |
|
|
188
|
+
| Markdown body | The `body` column, if the table has one. |
|
|
189
|
+
|
|
190
|
+
Folder names default to the SQL table name. Override per table:
|
|
191
|
+
|
|
192
|
+
```typescript
|
|
193
|
+
await drizzleMd({
|
|
194
|
+
root: 'content',
|
|
195
|
+
schema: { notes },
|
|
196
|
+
tables: {
|
|
197
|
+
notes: { dir: 'my-notes', key: 'slug', body: 'content' }, // body: false skips the body
|
|
198
|
+
},
|
|
199
|
+
});
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
Values are coerced to the Drizzle column type:
|
|
203
|
+
|
|
204
|
+
| Column | Frontmatter |
|
|
205
|
+
| --- | --- |
|
|
206
|
+
| `text()` | strings; numbers and booleans become strings; `enum` values are checked |
|
|
207
|
+
| `integer()`, `real()` | numbers; `integer()` must be a whole number |
|
|
208
|
+
| `integer({ mode: 'boolean' })` | `true` / `false` |
|
|
209
|
+
| `integer({ mode: 'timestamp' \| 'timestamp_ms' })` | ISO 8601 dates, such as `2026-11-23` or `2026-11-23T09:00:00+09:00` |
|
|
210
|
+
| `text({ mode: 'json' })`, `blob({ mode: 'json' })` | any YAML value, including nested lists and mappings |
|
|
211
|
+
| `blob({ mode: 'bigint' })` | whole numbers or digit strings |
|
|
212
|
+
|
|
213
|
+
Missing keys get the column's default (`.default()`, `.$defaultFn()`, or a SQL default). Frontmatter keys that match no column are ignored and counted in `md.report()`, so you can spot schema drift. A frontmatter key named like the key or body column is ignored too: the file name and the body win.
|
|
214
|
+
|
|
215
|
+
## Invalid files
|
|
216
|
+
|
|
217
|
+
This works the same in every entry point. A file is invalid when its YAML is broken, a required column (`required: true`, or `notNull` without a default in Drizzle) is missing, or a value doesn't fit its column. By default the first load throws an error listing every problem:
|
|
218
|
+
|
|
219
|
+
```typescript
|
|
220
|
+
import { drizzleMd, findMarkdownSqlError } from 'markdown-sql/drizzle';
|
|
221
|
+
|
|
222
|
+
try {
|
|
223
|
+
await drizzleMd({ root: 'content', schema });
|
|
224
|
+
} catch (error) {
|
|
225
|
+
for (const d of findMarkdownSqlError(error)?.diagnostics ?? []) {
|
|
226
|
+
console.error(`${d.file}: ${d.message}`); // posts/bad.md: expected a number, got string "many"
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
With `onInvalid: 'skip'` invalid files are left out and reported instead:
|
|
232
|
+
|
|
233
|
+
```typescript
|
|
234
|
+
const md = await drizzleMd({
|
|
235
|
+
root: 'content',
|
|
236
|
+
schema,
|
|
237
|
+
onInvalid: 'skip',
|
|
238
|
+
onDiagnostic: (d) => console.warn(`${d.file}: ${d.message}`),
|
|
239
|
+
});
|
|
240
|
+
md.diagnostics(); // current problems
|
|
241
|
+
md.report(); // { schemaHash, tables: [{ table, dir, rows, skipped, unknownKeys }], diagnostics }
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
## Watching for changes
|
|
245
|
+
|
|
246
|
+
The watcher is shared by every entry point.
|
|
247
|
+
|
|
248
|
+
```typescript
|
|
249
|
+
const md = await markdownSql({ root: 'content', watch: true });
|
|
250
|
+
// or later: md.watch({ debounceMs: 50 });
|
|
251
|
+
|
|
252
|
+
const unsubscribe = md.subscribe((events) => {
|
|
253
|
+
for (const event of events) {
|
|
254
|
+
console.log(event.type, event.table, event.key); // 'add' | 'change' | 'unlink' | 'invalid'
|
|
255
|
+
}
|
|
256
|
+
});
|
|
257
|
+
|
|
258
|
+
// ...
|
|
259
|
+
unsubscribe();
|
|
260
|
+
await md.close();
|
|
261
|
+
```
|
|
262
|
+
|
|
263
|
+
The watcher uses `fs.watch` on each table folder. Events are debounced per file, each file is hashed so saves without changes are skipped, and editor files (dotfiles such as `.post.md.swp`, `*~`, `#post.md#`, `*.tmp`) are ignored. Atomic saves (write a temp file, then rename) work. While watching, invalid files are always skipped and reported, so one typo doesn't stop your dev server; the row comes back once the file is fixed. `md.reload()` re-scans everything by hand.
|
|
264
|
+
|
|
265
|
+
## Read-only
|
|
266
|
+
|
|
267
|
+
Version 1 doesn't write files. `md.query()` and `md.sql` accept only `SELECT`, `WITH`, `VALUES` and `EXPLAIN`, and SQLite's `query_only` mode backs that up, so writes hidden in `WITH` fail too. Any `insert`, `update`, `delete`, DDL or `PRAGMA` sent through `md.db` in `markdown-sql/drizzle` is rejected with a `MarkdownSqlError` whose `code` is `READ_ONLY`. Drizzle wraps it in its own `DrizzleQueryError`, so check with `isMarkdownSqlError(error, 'READ_ONLY')` or `findMarkdownSqlError(error)`.
|
|
268
|
+
|
|
269
|
+
## Postgres with PGlite (`markdown-sql/pg`)
|
|
270
|
+
|
|
271
|
+
**Same function, different import.** Both Drizzle entry points export `drizzleMd` with the same options and the same result. The import path picks the engine:
|
|
272
|
+
|
|
273
|
+
```typescript
|
|
274
|
+
import { drizzleMd } from 'markdown-sql/drizzle'; // SQLite (better-sqlite3 or node:sqlite), sqliteTable schemas
|
|
275
|
+
import { drizzleMd } from 'markdown-sql/pg'; // PGlite (Postgres), pgTable schemas
|
|
276
|
+
```
|
|
277
|
+
|
|
278
|
+
`markdown-sql/pg` builds the same index in [PGlite](https://pglite.dev), Postgres compiled to WebAssembly, so you can write `pgTable` schemas and use Postgres features: array operators, `jsonb`, full-text search, `pg_trgm` and GIN indexes. The watcher, diagnostics, `report()`, `reload()`, `subscribe()`, `settled()` and `close()` behave exactly as in the SQLite entry points.
|
|
279
|
+
|
|
280
|
+
```bash
|
|
281
|
+
npm install markdown-sql drizzle-orm @electric-sql/pglite
|
|
282
|
+
# optional, for faster startup:
|
|
283
|
+
npm install @electric-sql/pglite-prepopulatedfs
|
|
284
|
+
```
|
|
285
|
+
|
|
286
|
+
```typescript
|
|
287
|
+
import { arrayContains, eq } from 'drizzle-orm';
|
|
288
|
+
import { boolean, jsonb, pgEnum, pgTable, text, timestamp } from 'drizzle-orm/pg-core';
|
|
289
|
+
import { drizzleMd } from 'markdown-sql/pg';
|
|
290
|
+
|
|
291
|
+
export const status = pgEnum('status', ['idea', 'published']);
|
|
292
|
+
|
|
293
|
+
export const posts = pgTable('posts', {
|
|
294
|
+
id: text().primaryKey(),
|
|
295
|
+
title: text().notNull(),
|
|
296
|
+
published: timestamp({ withTimezone: true }).notNull(),
|
|
297
|
+
draft: boolean().notNull().default(false),
|
|
298
|
+
tags: text().array().notNull().default([]), // a YAML list
|
|
299
|
+
meta: jsonb().$type<{ readingTime: number }>(), // a YAML mapping
|
|
300
|
+
status: status(),
|
|
301
|
+
body: text().notNull(),
|
|
302
|
+
});
|
|
303
|
+
|
|
304
|
+
const md = await drizzleMd({ root: 'content', schema: { status, posts }, watch: true });
|
|
305
|
+
|
|
306
|
+
const tagged = await md.db
|
|
307
|
+
.select()
|
|
308
|
+
.from(posts)
|
|
309
|
+
.where(arrayContains(posts.tags, ['drizzle']));
|
|
310
|
+
|
|
311
|
+
// Re-runs whenever a file in posts/ changes; rows are typed and mapped by Drizzle.
|
|
312
|
+
const live = await md.live(
|
|
313
|
+
md.db.select({ id: posts.id }).from(posts).where(eq(posts.draft, false)),
|
|
314
|
+
(rows) => console.log(rows),
|
|
315
|
+
);
|
|
316
|
+
await live.unsubscribe();
|
|
317
|
+
await md.close();
|
|
318
|
+
```
|
|
319
|
+
|
|
320
|
+
YAML lists fill array columns (`text().array()`, enum arrays, `integer().array()`, each item checked against the element type), and mappings or lists fill `json()` / `jsonb()` columns. `pgEnum` types are created for you. On the first load each folder is bulk-loaded with one `COPY … FROM '/dev/blob'`; if Postgres rejects a row (say a `varchar(40)` overflow), MarkdownSQL retries file by file and reports only that file as a `sql-error`.
|
|
321
|
+
|
|
322
|
+
Options on top of the SQLite ones:
|
|
323
|
+
|
|
324
|
+
| Option | Meaning |
|
|
325
|
+
| --- | --- |
|
|
326
|
+
| `prepopulated` | Start from the `@electric-sql/pglite-prepopulatedfs` snapshot instead of running initdb (about 0.5 s instead of 1.4 s). Default: use it when it is installed **and** its version is exactly the installed `@electric-sql/pglite` version; on a mismatch or a failed load PGlite starts normally and `onDiagnostic` gets a `startup-warning`. `true` requires it (a missing package, a mismatch or a failed load is a `CONFIG` error). `false` skips it. |
|
|
327
|
+
| `pglite` | Extra PGlite options, such as `extensions: { pg_trgm }` or `debug`. The data directory is always in memory. |
|
|
328
|
+
| `setup` | SQL run once as the database owner after the tables are created and before the files load, e.g. `CREATE EXTENSION pg_trgm`. Trusted code only, see below. |
|
|
329
|
+
|
|
330
|
+
**Indexes.** `index()` and `uniqueIndex()` declared in a `pgTable` are created for you:
|
|
331
|
+
|
|
332
|
+
- **Columns:** single or multiple, with an operator class (`t.title.op('gin_trgm_ops')`), `.asc()` / `.desc()` and `.nullsFirst()` / `.nullsLast()`.
|
|
333
|
+
- **Expressions:** `sql` expressions, e.g. ``sql`lower(${t.title})` ``.
|
|
334
|
+
- **Methods:** any method set with `.using()`, such as gin, gist, brin or hash.
|
|
335
|
+
- **Clauses:** `.where()` for partial indexes and `.with()` storage options.
|
|
336
|
+
|
|
337
|
+
Unique indexes exist before the files load, so a file that repeats a unique value is reported as a `sql-error` and the other files still load. Other indexes are built once after the first load, which is faster than updating them row by row, followed by `ANALYZE`.
|
|
338
|
+
|
|
339
|
+
There are a few limits:
|
|
340
|
+
|
|
341
|
+
- `.concurrently()` is ignored.
|
|
342
|
+
- Expressions and `.where()` must not contain bound values: write literals into the SQL text or use `sql.raw()`. Otherwise you get a `CONFIG` error.
|
|
343
|
+
- An index Postgres cannot build, such as an operator class from an extension you didn't create in `setup`, fails startup with a `CONFIG` error that names the index.
|
|
344
|
+
|
|
345
|
+
```typescript
|
|
346
|
+
import { pg_trgm } from '@electric-sql/pglite/contrib/pg_trgm';
|
|
347
|
+
import { index, pgTable, text } from 'drizzle-orm/pg-core';
|
|
348
|
+
|
|
349
|
+
export const posts = pgTable(
|
|
350
|
+
'posts',
|
|
351
|
+
{ id: text().primaryKey(), title: text().notNull(), tags: text().array().notNull().default([]) },
|
|
352
|
+
(t) => [
|
|
353
|
+
index('posts_tags_gin').using('gin', t.tags),
|
|
354
|
+
index('posts_title_trgm').using('gin', t.title.op('gin_trgm_ops')),
|
|
355
|
+
],
|
|
356
|
+
);
|
|
357
|
+
|
|
358
|
+
const md = await drizzleMd({
|
|
359
|
+
root: 'content',
|
|
360
|
+
schema: { posts },
|
|
361
|
+
pglite: { extensions: { pg_trgm } },
|
|
362
|
+
setup: 'CREATE EXTENSION pg_trgm', // the extension must exist before its index is built
|
|
363
|
+
});
|
|
364
|
+
```
|
|
365
|
+
|
|
366
|
+
> **`setup` is trusted startup code.** It runs with full database rights, outside the read-only guard below. Treat it like a migration you wrote yourself: never build it from user input, request data, markdown file contents or anything else untrusted.
|
|
367
|
+
|
|
368
|
+
**Read-only.** Every statement from `md.db` runs in its own `READ ONLY` transaction, as a select-only `md_reader` role, and is always rolled back. Writes, DDL, `DO` blocks, `SET` and writes hidden in `WITH` are rejected with the same `READ_ONLY` error code as the SQLite entry points. `md.live()` first runs the query through that read-only path before PGlite's live extension sees it.
|
|
369
|
+
|
|
370
|
+
**Trade-offs.** Pick `markdown-sql/pg` when you want Postgres features or already use Postgres schemas; the SQLite entry points stay the lighter default.
|
|
371
|
+
|
|
372
|
+
| | SQLite (`markdown-sql`, `markdown-sql/drizzle`) | PGlite (`markdown-sql/pg`) |
|
|
373
|
+
| --- | --- | --- |
|
|
374
|
+
| Memory | a few MB | about 570–700 MB RSS per instance (WebAssembly heap) |
|
|
375
|
+
| Startup | milliseconds | about 0.5 s with the snapshot, 1.4 s without |
|
|
376
|
+
| Per-query overhead | microseconds | about 0.2 ms (transaction, role switch, rollback) |
|
|
377
|
+
| Runtimes | Node.js | Node.js; not Cloudflare Workers (PGlite needs more memory and WebAssembly than Workers allow) |
|
|
378
|
+
| Extras | | arrays, `jsonb`, enums, extensions, schema-declared GIN/GiST/expression indexes, live queries |
|
|
379
|
+
|
|
380
|
+
## Limitations
|
|
381
|
+
|
|
382
|
+
- Read-only in version 1: edit the markdown files to change data.
|
|
383
|
+
- One folder per table and one level deep: files in sub-folders are not read.
|
|
384
|
+
- The plain `markdown-sql` entry infers columns once, on the first load. A frontmatter key that first appears later is counted in `report()` as an unknown key until you restart or declare it in `columns`.
|
|
385
|
+
- The plain `markdown-sql` entry only offers SQLite; Postgres is available through `markdown-sql/pg` with a Drizzle schema.
|
|
386
|
+
- `markdown-sql/drizzle` and `markdown-sql/pg`: generated columns, `blob({ mode: 'buffer' })` columns and unique or foreign key constraints are not applied to the index. Foreign keys still work in joins and relations.
|
|
387
|
+
- The index lives in memory and is rebuilt on every start.
|
|
388
|
+
- The watcher doesn't notice a table folder that is created after `watch()` starts.
|
|
389
|
+
- `markdown-sql/pg`: only tables and enums in the default `public` schema; foreign keys, checks and generated columns declared in `pgTable` are not applied yet (indexes and unique indexes are).
|
|
390
|
+
|
|
391
|
+
## Roadmap
|
|
392
|
+
|
|
393
|
+
- **Writes:** `insert`, `update` and `delete` through SQL and Drizzle that create, rewrite or remove the matching files, keeping unknown frontmatter keys and key order so git diffs stay small.
|
|
394
|
+
- **File migrations:** a drizzle-kit style diff between two schemas that renames, adds and drops frontmatter keys in the files.
|
|
395
|
+
- **Index cache:** keep the index on disk and rebuild only when the schema hash or files change.
|
|
396
|
+
- Nested folders and per-table glob patterns.
|
|
397
|
+
|
|
398
|
+
See [docs/design.md](docs/design.md) for the architecture and the migrations plan.
|
|
399
|
+
|
|
400
|
+
## Migrating from drizzle-md
|
|
401
|
+
|
|
402
|
+
MarkdownSQL is the new name of [`drizzle-md`](https://www.npmjs.com/package/drizzle-md) (0.1.0), because the core is querying markdown and Drizzle is now optional. The Drizzle API is unchanged apart from the import path and the error helper names:
|
|
403
|
+
|
|
404
|
+
| drizzle-md 0.1.0 | MarkdownSQL 0.1.0 |
|
|
405
|
+
| --- | --- |
|
|
406
|
+
| `npm install drizzle-md drizzle-orm` | `npm install markdown-sql drizzle-orm` |
|
|
407
|
+
| `import { drizzleMd } from 'drizzle-md'` | `import { drizzleMd } from 'markdown-sql/drizzle'` |
|
|
408
|
+
| `import { drizzleMd } from 'drizzle-md/pg'` | `import { drizzleMd } from 'markdown-sql/pg'` |
|
|
409
|
+
| `findDrizzleMdError`, `isDrizzleMdError` | `findMarkdownSqlError`, `isMarkdownSqlError` |
|
|
410
|
+
| types `DrizzleMdError`, `DrizzleMdErrorCode`, `DrizzleMdIndex` | `MarkdownSqlError`, `MarkdownSqlErrorCode`, `MarkdownSqlIndex` |
|
|
411
|
+
| `error.name === 'DrizzleMdError'` | `error.name === 'MarkdownSqlError'` |
|
|
412
|
+
| error messages start with `drizzle-md` | they start with `MarkdownSQL` |
|
|
413
|
+
|
|
414
|
+
Options, results, error codes (`READ_ONLY`, `VALIDATION`, `CONFIG`, `CLOSED`), diagnostics, the watcher and `markdown-sql/pg`'s `live()`, `setup`, `prepopulated` and indexes behave exactly as before. `drizzle-orm` is now an optional peer dependency: install it yourself (you already do with drizzle-md). If you don't need Drizzle, the new `markdown-sql` entry point queries the same folders with plain SQL.
|
|
415
|
+
|
|
416
|
+
## Contributing
|
|
417
|
+
|
|
418
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md) for the setup, the coding conventions and the lint rules.
|
|
419
|
+
|
|
420
|
+
## License
|
|
421
|
+
|
|
422
|
+
[Apache-2.0](LICENSE)
|