cloudflare-d1 0.1.0

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.
data/.rubocop.yml ADDED
@@ -0,0 +1,13 @@
1
+ AllCops:
2
+ TargetRubyVersion: 2.6
3
+
4
+ Style/StringLiterals:
5
+ Enabled: true
6
+ EnforcedStyle: double_quotes
7
+
8
+ Style/StringLiteralsInInterpolation:
9
+ Enabled: true
10
+ EnforcedStyle: double_quotes
11
+
12
+ Layout/LineLength:
13
+ Max: 120
data/CHANGELOG.md ADDED
@@ -0,0 +1,17 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2024-12-20
4
+
5
+ ### Added
6
+
7
+ - ActiveRecord adapter for Cloudflare D1
8
+ - Sequel adapter for Cloudflare D1
9
+ - HTTP client for D1 REST API
10
+ - Database management (create, delete, list databases)
11
+ - Rake tasks for ActiveRecord migrations
12
+ - Rake tasks for Sequel migrations
13
+ - Local development support with SQLite
14
+ - Roda + Cloudflare Containers example
15
+ - Complete test suite (89 tests, 172 assertions)
16
+ - CI/CD with GitHub Actions
17
+ - Automated gem releases
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at ben@dee.mx. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
@@ -0,0 +1,365 @@
1
+ # Database Management
2
+
3
+ This document explains how to create, manage, and migrate Cloudflare D1 databases using both ActiveRecord and Sequel.
4
+
5
+ ## ActiveRecord (Rails)
6
+
7
+ ### Configuration
8
+
9
+ Add to your `config/database.yml`:
10
+
11
+ ```yaml
12
+ development:
13
+ adapter: cloudflare_d1
14
+ account_id: <%= ENV['CLOUDFLARE_ACCOUNT_ID'] %>
15
+ api_token: <%= ENV['CLOUDFLARE_API_TOKEN'] %>
16
+ database_id: <%= ENV['DATABASE_ID'] %> # UUID of your D1 database
17
+ ```
18
+
19
+ Or use environment variables:
20
+ ```bash
21
+ export CLOUDFLARE_ACCOUNT_ID=your_account_id
22
+ export CLOUDFLARE_API_TOKEN=your_api_token
23
+ export DATABASE_ID=your_database_uuid
24
+ ```
25
+
26
+ ### Available Rake Tasks
27
+
28
+ #### Create Database
29
+
30
+ ```bash
31
+ # For Rails applications
32
+ rake db:create
33
+ ```
34
+
35
+ This will create a new D1 database and return its UUID. Add the UUID to your `database.yml` or environment variables.
36
+
37
+ #### Drop Database
38
+
39
+ ```bash
40
+ rake db:drop
41
+ ```
42
+
43
+ Deletes the D1 database. **This is irreversible!**
44
+
45
+ #### List Databases
46
+
47
+ ```bash
48
+ rake db:list
49
+ ```
50
+
51
+ Shows all D1 databases in your Cloudflare account.
52
+
53
+ #### Run Migrations
54
+
55
+ ```bash
56
+ # Run all pending migrations
57
+ rake db:migrate
58
+
59
+ # Run migrations with verbose output
60
+ VERBOSE=true rake db:migrate
61
+ ```
62
+
63
+ #### Rollback Migrations
64
+
65
+ ```bash
66
+ # Rollback one migration
67
+ rake db:rollback
68
+
69
+ # Rollback multiple migrations
70
+ rake db:rollback STEP=3
71
+ ```
72
+
73
+ #### Migration Status
74
+
75
+ ```bash
76
+ rake db:migrate_status
77
+ ```
78
+
79
+ Shows which migrations have been applied.
80
+
81
+ #### Reset Database
82
+
83
+ ```bash
84
+ # Drop, create, and migrate (WARNING: destroys all data!)
85
+ rake db:reset
86
+ ```
87
+
88
+ #### Setup Database
89
+
90
+ ```bash
91
+ # Create and migrate (for initial setup)
92
+ rake db:setup
93
+ ```
94
+
95
+ ### Creating Migrations
96
+
97
+ Use standard Rails migration generators:
98
+
99
+ ```bash
100
+ rails generate migration CreateUsers email:string
101
+ rails generate migration AddIndexToUsers email:index
102
+ ```
103
+
104
+ Example migration:
105
+
106
+ ```ruby
107
+ class CreateUsers < ActiveRecord::Migration[7.0]
108
+ def change
109
+ create_table :users do |t|
110
+ t.string :email, null: false
111
+ t.timestamps
112
+ end
113
+
114
+ add_index :users, :email, unique: true
115
+ end
116
+ end
117
+ ```
118
+
119
+ ### Limitations
120
+
121
+ - **No DDL transactions**: Schema changes are not wrapped in transactions
122
+ - **No savepoints**: Transaction savepoints are not supported
123
+ - **No concurrent migrations**: Each migration runs as separate HTTP requests
124
+
125
+ ## Sequel
126
+
127
+ ### Configuration
128
+
129
+ Connect using a URL or hash:
130
+
131
+ ```ruby
132
+ # Using URL
133
+ DB = Sequel.connect(
134
+ "cloudflare_d1://",
135
+ adapter: :cloudflare_d1,
136
+ account_id: ENV['CLOUDFLARE_ACCOUNT_ID'],
137
+ api_token: ENV['CLOUDFLARE_API_TOKEN'],
138
+ database: ENV['DATABASE_ID']
139
+ )
140
+
141
+ # Or using hash
142
+ DB = Sequel.connect(
143
+ adapter: :cloudflare_d1,
144
+ account_id: ENV['CLOUDFLARE_ACCOUNT_ID'],
145
+ api_token: ENV['CLOUDFLARE_API_TOKEN'],
146
+ database: ENV['DATABASE_ID']
147
+ )
148
+ ```
149
+
150
+ ### Available Rake Tasks
151
+
152
+ All Sequel tasks are under the `sequel:db` namespace:
153
+
154
+ #### Create Database
155
+
156
+ ```bash
157
+ DATABASE_NAME=my_app_db rake sequel:db:create
158
+ ```
159
+
160
+ #### Drop Database
161
+
162
+ ```bash
163
+ DATABASE_ID=your_database_uuid rake sequel:db:drop
164
+ ```
165
+
166
+ #### List Databases
167
+
168
+ ```bash
169
+ rake sequel:db:list
170
+ ```
171
+
172
+ #### Run Migrations
173
+
174
+ ```bash
175
+ # Run all migrations
176
+ DATABASE_URL=cloudflare_d1://your_database_uuid rake sequel:db:migrate
177
+
178
+ # Run to specific version
179
+ DATABASE_URL=cloudflare_d1://your_database_uuid rake sequel:db:migrate[42]
180
+
181
+ # Custom migrations path
182
+ MIGRATIONS_PATH=db/migrations DATABASE_URL=... rake sequel:db:migrate
183
+ ```
184
+
185
+ #### Rollback Migrations
186
+
187
+ ```bash
188
+ # Rollback one migration
189
+ DATABASE_URL=... rake sequel:db:rollback
190
+
191
+ # Rollback multiple migrations
192
+ DATABASE_URL=... rake sequel:db:rollback[3]
193
+ ```
194
+
195
+ #### Migration Status
196
+
197
+ ```bash
198
+ DATABASE_URL=... rake sequel:db:status
199
+ ```
200
+
201
+ #### Reset Database
202
+
203
+ ```bash
204
+ DATABASE_URL=... rake sequel:db:reset
205
+ ```
206
+
207
+ #### Setup Database
208
+
209
+ ```bash
210
+ DATABASE_NAME=my_app_db DATABASE_URL=... rake sequel:db:setup
211
+ ```
212
+
213
+ ### Creating Migrations
214
+
215
+ Create migration files in `db/migrations/` with format: `001_description.rb`
216
+
217
+ ```ruby
218
+ # db/migrations/001_create_users.rb
219
+ Sequel.migration do
220
+ up do
221
+ create_table(:users) do
222
+ primary_key :id
223
+ String :email, null: false, unique: true
224
+ DateTime :created_at
225
+ DateTime :updated_at
226
+ end
227
+ end
228
+
229
+ down do
230
+ drop_table(:users)
231
+ end
232
+ end
233
+ ```
234
+
235
+ Or use the `change` method for reversible migrations:
236
+
237
+ ```ruby
238
+ # db/migrations/002_add_name_to_users.rb
239
+ Sequel.migration do
240
+ change do
241
+ alter_table(:users) do
242
+ add_column :name, String
243
+ end
244
+ end
245
+ end
246
+ ```
247
+
248
+ ### Running Migrations from Command Line
249
+
250
+ ```bash
251
+ sequel -m db/migrations cloudflare_d1://your_database_uuid
252
+ ```
253
+
254
+ ### Limitations
255
+
256
+ - **No transactions**: Migrations run without transaction support
257
+ - **No concurrent access**: Each operation is a separate HTTP request
258
+ - **No connection pooling**: API-based connections don't benefit from traditional pooling
259
+
260
+ ## Environment Variables
261
+
262
+ Both ActiveRecord and Sequel tasks require:
263
+
264
+ ```bash
265
+ export CLOUDFLARE_ACCOUNT_ID=your_account_id
266
+ export CLOUDFLARE_API_TOKEN=your_api_token
267
+ ```
268
+
269
+ For ActiveRecord:
270
+ ```bash
271
+ export DATABASE_ID=your_database_uuid
272
+ ```
273
+
274
+ For Sequel:
275
+ ```bash
276
+ export DATABASE_URL=cloudflare_d1://your_database_uuid
277
+ export DATABASE_NAME=my_app_db # Only for creation
278
+ export MIGRATIONS_PATH=db/migrations # Optional, defaults to db/migrations
279
+ ```
280
+
281
+ ## Best Practices
282
+
283
+ ### 1. Database Creation
284
+
285
+ Always note the UUID returned when creating a database:
286
+
287
+ ```bash
288
+ $ rake db:create
289
+ Created database: my_app_db (a1b2c3d4-e5f6-7890-abcd-ef1234567890)
290
+
291
+ Add this to your database.yml:
292
+ database_id: a1b2c3d4-e5f6-7890-abcd-ef1234567890
293
+ ```
294
+
295
+ ### 2. Migration Safety
296
+
297
+ Since D1 doesn't support DDL transactions, test migrations carefully:
298
+
299
+ - Use staging databases for testing
300
+ - Backup important data before migrations (export via queries)
301
+ - Write reversible migrations with both `up` and `down` methods
302
+
303
+ ### 3. Schema Changes
304
+
305
+ Some operations are not reversible in SQLite:
306
+ - Dropping columns (SQLite doesn't support `DROP COLUMN`)
307
+ - Changing column types (requires table recreation)
308
+ - Renaming columns (requires table recreation)
309
+
310
+ For these, write explicit `up` and `down` methods.
311
+
312
+ ### 4. Connection Configuration
313
+
314
+ Store credentials securely:
315
+ - Use environment variables (never commit API tokens)
316
+ - Use Rails credentials or encrypted secrets
317
+ - Restrict API token permissions to only D1 databases
318
+
319
+ ## Troubleshooting
320
+
321
+ ### "database_id is required"
322
+
323
+ Make sure your configuration includes the UUID:
324
+
325
+ ```yaml
326
+ # database.yml
327
+ database_id: a1b2c3d4-e5f6-7890-abcd-ef1234567890
328
+ ```
329
+
330
+ Or set environment variable:
331
+ ```bash
332
+ export DATABASE_ID=a1b2c3d4-e5f6-7890-abcd-ef1234567890
333
+ ```
334
+
335
+ ### "Real HTTP connections are disabled"
336
+
337
+ In test environment with WebMock, stub the D1 API calls:
338
+
339
+ ```ruby
340
+ stub_request(:post, /api.cloudflare.com/)
341
+ .to_return(status: 200, body: { success: true, result: [...] }.to_json)
342
+ ```
343
+
344
+ ### "Table already exists"
345
+
346
+ Drop and recreate the database, or use migrations to detect existing tables:
347
+
348
+ ```ruby
349
+ create_table?(:users) do # ? makes it conditional
350
+ # ...
351
+ end
352
+ ```
353
+
354
+ ## API Rate Limits
355
+
356
+ Cloudflare D1 API has rate limits:
357
+ - Migrations run sequentially (one HTTP request per SQL statement)
358
+ - Large migrations may take time
359
+ - Consider batching operations when possible
360
+
361
+ ## See Also
362
+
363
+ - [Cloudflare D1 Documentation](https://developers.cloudflare.com/d1/)
364
+ - [ActiveRecord Migrations Guide](https://guides.rubyonrails.org/active_record_migrations.html)
365
+ - [Sequel Migrations Documentation](https://sequel.jeremyevans.net/rdoc/files/doc/migration_rdoc.html)
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Ben
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.