├── .gitignore
├── CONTRIBUTING.md
├── LICENSE
├── Makefile
├── README.md
├── TODO.md
├── docs
└── installation.md
├── dune-project
└── src
├── README.md
├── data_engine.ml
├── db_engine.ml
├── dune
├── http_engine.ml
├── io_engine.ml
├── lexer.mll
├── main.ml
└── parser.mly
/.gitignore:
--------------------------------------------------------------------------------
1 | sql
2 | test
3 | _build/
4 | .vscode/
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing to sqlc
2 |
3 | Thank you for your interest in contributing to sqlc! We welcome contributions from the community to help improve our project.
4 |
5 | ## Getting Started
6 |
7 | To get started with contributing, please follow these steps:
8 |
9 | 1. Fork the repository.
10 | 2. Clone the forked repository to your local machine.
11 | 3. Create a new branch for your changes.
12 | 4. Make your desired changes to the codebase.
13 | 5. Test your changes thoroughly.
14 | 6. Commit your changes with descriptive commit messages.
15 | 7. Push your changes to your forked repository.
16 | 8. Submit a pull request to the main repository.
17 |
18 | ## Code Style
19 |
20 | We follow a specific code style in our project. Please make sure to adhere to the following guidelines:
21 |
22 | - Use consistent indentation (spaces or tabs).
23 | - Follow naming conventions for variables, functions, and classes.
24 | - Write clear and concise comments.
25 | - Keep lines of code within a reasonable length.
26 |
27 | ## Reporting Issues
28 |
29 | If you encounter any issues or have suggestions for improvement, please open an issue in the issue tracker. Provide as much detail as possible to help us understand and reproduce the problem.
30 |
31 | ## Contact
32 |
33 | If you have any questions or need further assistance, feel free to reach out to us at [xeonds@stu.xidian.edu.cn].
34 |
35 | We appreciate your contributions and look forward to working with you!
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | # GNU GENERAL PUBLIC LICENSE
2 |
3 | Version 3, 29 June 2007
4 |
5 | Copyright (C) 2007 Free Software Foundation, Inc.
6 |
7 |
8 | Everyone is permitted to copy and distribute verbatim copies of this
9 | license document, but changing it is not allowed.
10 |
11 | ## Preamble
12 |
13 | The GNU General Public License is a free, copyleft license for
14 | software and other kinds of works.
15 |
16 | The licenses for most software and other practical works are designed
17 | to take away your freedom to share and change the works. By contrast,
18 | the GNU General Public License is intended to guarantee your freedom
19 | to share and change all versions of a program--to make sure it remains
20 | free software for all its users. We, the Free Software Foundation, use
21 | the GNU General Public License for most of our software; it applies
22 | also to any other work released this way by its authors. You can apply
23 | it to your programs, too.
24 |
25 | When we speak of free software, we are referring to freedom, not
26 | price. Our General Public Licenses are designed to make sure that you
27 | have the freedom to distribute copies of free software (and charge for
28 | them if you wish), that you receive source code or can get it if you
29 | want it, that you can change the software or use pieces of it in new
30 | free programs, and that you know you can do these things.
31 |
32 | To protect your rights, we need to prevent others from denying you
33 | these rights or asking you to surrender the rights. Therefore, you
34 | have certain responsibilities if you distribute copies of the
35 | software, or if you modify it: responsibilities to respect the freedom
36 | of others.
37 |
38 | For example, if you distribute copies of such a program, whether
39 | gratis or for a fee, you must pass on to the recipients the same
40 | freedoms that you received. You must make sure that they, too, receive
41 | or can get the source code. And you must show them these terms so they
42 | know their rights.
43 |
44 | Developers that use the GNU GPL protect your rights with two steps:
45 | (1) assert copyright on the software, and (2) offer you this License
46 | giving you legal permission to copy, distribute and/or modify it.
47 |
48 | For the developers' and authors' protection, the GPL clearly explains
49 | that there is no warranty for this free software. For both users' and
50 | authors' sake, the GPL requires that modified versions be marked as
51 | changed, so that their problems will not be attributed erroneously to
52 | authors of previous versions.
53 |
54 | Some devices are designed to deny users access to install or run
55 | modified versions of the software inside them, although the
56 | manufacturer can do so. This is fundamentally incompatible with the
57 | aim of protecting users' freedom to change the software. The
58 | systematic pattern of such abuse occurs in the area of products for
59 | individuals to use, which is precisely where it is most unacceptable.
60 | Therefore, we have designed this version of the GPL to prohibit the
61 | practice for those products. If such problems arise substantially in
62 | other domains, we stand ready to extend this provision to those
63 | domains in future versions of the GPL, as needed to protect the
64 | freedom of users.
65 |
66 | Finally, every program is threatened constantly by software patents.
67 | States should not allow patents to restrict development and use of
68 | software on general-purpose computers, but in those that do, we wish
69 | to avoid the special danger that patents applied to a free program
70 | could make it effectively proprietary. To prevent this, the GPL
71 | assures that patents cannot be used to render the program non-free.
72 |
73 | The precise terms and conditions for copying, distribution and
74 | modification follow.
75 |
76 | ## TERMS AND CONDITIONS
77 |
78 | ### 0. Definitions.
79 |
80 | "This License" refers to version 3 of the GNU General Public License.
81 |
82 | "Copyright" also means copyright-like laws that apply to other kinds
83 | of works, such as semiconductor masks.
84 |
85 | "The Program" refers to any copyrightable work licensed under this
86 | License. Each licensee is addressed as "you". "Licensees" and
87 | "recipients" may be individuals or organizations.
88 |
89 | To "modify" a work means to copy from or adapt all or part of the work
90 | in a fashion requiring copyright permission, other than the making of
91 | an exact copy. The resulting work is called a "modified version" of
92 | the earlier work or a work "based on" the earlier work.
93 |
94 | A "covered work" means either the unmodified Program or a work based
95 | on the Program.
96 |
97 | To "propagate" a work means to do anything with it that, without
98 | permission, would make you directly or secondarily liable for
99 | infringement under applicable copyright law, except executing it on a
100 | computer or modifying a private copy. Propagation includes copying,
101 | distribution (with or without modification), making available to the
102 | public, and in some countries other activities as well.
103 |
104 | To "convey" a work means any kind of propagation that enables other
105 | parties to make or receive copies. Mere interaction with a user
106 | through a computer network, with no transfer of a copy, is not
107 | conveying.
108 |
109 | An interactive user interface displays "Appropriate Legal Notices" to
110 | the extent that it includes a convenient and prominently visible
111 | feature that (1) displays an appropriate copyright notice, and (2)
112 | tells the user that there is no warranty for the work (except to the
113 | extent that warranties are provided), that licensees may convey the
114 | work under this License, and how to view a copy of this License. If
115 | the interface presents a list of user commands or options, such as a
116 | menu, a prominent item in the list meets this criterion.
117 |
118 | ### 1. Source Code.
119 |
120 | The "source code" for a work means the preferred form of the work for
121 | making modifications to it. "Object code" means any non-source form of
122 | a work.
123 |
124 | A "Standard Interface" means an interface that either is an official
125 | standard defined by a recognized standards body, or, in the case of
126 | interfaces specified for a particular programming language, one that
127 | is widely used among developers working in that language.
128 |
129 | The "System Libraries" of an executable work include anything, other
130 | than the work as a whole, that (a) is included in the normal form of
131 | packaging a Major Component, but which is not part of that Major
132 | Component, and (b) serves only to enable use of the work with that
133 | Major Component, or to implement a Standard Interface for which an
134 | implementation is available to the public in source code form. A
135 | "Major Component", in this context, means a major essential component
136 | (kernel, window system, and so on) of the specific operating system
137 | (if any) on which the executable work runs, or a compiler used to
138 | produce the work, or an object code interpreter used to run it.
139 |
140 | The "Corresponding Source" for a work in object code form means all
141 | the source code needed to generate, install, and (for an executable
142 | work) run the object code and to modify the work, including scripts to
143 | control those activities. However, it does not include the work's
144 | System Libraries, or general-purpose tools or generally available free
145 | programs which are used unmodified in performing those activities but
146 | which are not part of the work. For example, Corresponding Source
147 | includes interface definition files associated with source files for
148 | the work, and the source code for shared libraries and dynamically
149 | linked subprograms that the work is specifically designed to require,
150 | such as by intimate data communication or control flow between those
151 | subprograms and other parts of the work.
152 |
153 | The Corresponding Source need not include anything that users can
154 | regenerate automatically from other parts of the Corresponding Source.
155 |
156 | The Corresponding Source for a work in source code form is that same
157 | work.
158 |
159 | ### 2. Basic Permissions.
160 |
161 | All rights granted under this License are granted for the term of
162 | copyright on the Program, and are irrevocable provided the stated
163 | conditions are met. This License explicitly affirms your unlimited
164 | permission to run the unmodified Program. The output from running a
165 | covered work is covered by this License only if the output, given its
166 | content, constitutes a covered work. This License acknowledges your
167 | rights of fair use or other equivalent, as provided by copyright law.
168 |
169 | You may make, run and propagate covered works that you do not convey,
170 | without conditions so long as your license otherwise remains in force.
171 | You may convey covered works to others for the sole purpose of having
172 | them make modifications exclusively for you, or provide you with
173 | facilities for running those works, provided that you comply with the
174 | terms of this License in conveying all material for which you do not
175 | control copyright. Those thus making or running the covered works for
176 | you must do so exclusively on your behalf, under your direction and
177 | control, on terms that prohibit them from making any copies of your
178 | copyrighted material outside their relationship with you.
179 |
180 | Conveying under any other circumstances is permitted solely under the
181 | conditions stated below. Sublicensing is not allowed; section 10 makes
182 | it unnecessary.
183 |
184 | ### 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
185 |
186 | No covered work shall be deemed part of an effective technological
187 | measure under any applicable law fulfilling obligations under article
188 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
189 | similar laws prohibiting or restricting circumvention of such
190 | measures.
191 |
192 | When you convey a covered work, you waive any legal power to forbid
193 | circumvention of technological measures to the extent such
194 | circumvention is effected by exercising rights under this License with
195 | respect to the covered work, and you disclaim any intention to limit
196 | operation or modification of the work as a means of enforcing, against
197 | the work's users, your or third parties' legal rights to forbid
198 | circumvention of technological measures.
199 |
200 | ### 4. Conveying Verbatim Copies.
201 |
202 | You may convey verbatim copies of the Program's source code as you
203 | receive it, in any medium, provided that you conspicuously and
204 | appropriately publish on each copy an appropriate copyright notice;
205 | keep intact all notices stating that this License and any
206 | non-permissive terms added in accord with section 7 apply to the code;
207 | keep intact all notices of the absence of any warranty; and give all
208 | recipients a copy of this License along with the Program.
209 |
210 | You may charge any price or no price for each copy that you convey,
211 | and you may offer support or warranty protection for a fee.
212 |
213 | ### 5. Conveying Modified Source Versions.
214 |
215 | You may convey a work based on the Program, or the modifications to
216 | produce it from the Program, in the form of source code under the
217 | terms of section 4, provided that you also meet all of these
218 | conditions:
219 |
220 | - a) The work must carry prominent notices stating that you modified
221 | it, and giving a relevant date.
222 | - b) The work must carry prominent notices stating that it is
223 | released under this License and any conditions added under
224 | section 7. This requirement modifies the requirement in section 4
225 | to "keep intact all notices".
226 | - c) You must license the entire work, as a whole, under this
227 | License to anyone who comes into possession of a copy. This
228 | License will therefore apply, along with any applicable section 7
229 | additional terms, to the whole of the work, and all its parts,
230 | regardless of how they are packaged. This License gives no
231 | permission to license the work in any other way, but it does not
232 | invalidate such permission if you have separately received it.
233 | - d) If the work has interactive user interfaces, each must display
234 | Appropriate Legal Notices; however, if the Program has interactive
235 | interfaces that do not display Appropriate Legal Notices, your
236 | work need not make them do so.
237 |
238 | A compilation of a covered work with other separate and independent
239 | works, which are not by their nature extensions of the covered work,
240 | and which are not combined with it such as to form a larger program,
241 | in or on a volume of a storage or distribution medium, is called an
242 | "aggregate" if the compilation and its resulting copyright are not
243 | used to limit the access or legal rights of the compilation's users
244 | beyond what the individual works permit. Inclusion of a covered work
245 | in an aggregate does not cause this License to apply to the other
246 | parts of the aggregate.
247 |
248 | ### 6. Conveying Non-Source Forms.
249 |
250 | You may convey a covered work in object code form under the terms of
251 | sections 4 and 5, provided that you also convey the machine-readable
252 | Corresponding Source under the terms of this License, in one of these
253 | ways:
254 |
255 | - a) Convey the object code in, or embodied in, a physical product
256 | (including a physical distribution medium), accompanied by the
257 | Corresponding Source fixed on a durable physical medium
258 | customarily used for software interchange.
259 | - b) Convey the object code in, or embodied in, a physical product
260 | (including a physical distribution medium), accompanied by a
261 | written offer, valid for at least three years and valid for as
262 | long as you offer spare parts or customer support for that product
263 | model, to give anyone who possesses the object code either (1) a
264 | copy of the Corresponding Source for all the software in the
265 | product that is covered by this License, on a durable physical
266 | medium customarily used for software interchange, for a price no
267 | more than your reasonable cost of physically performing this
268 | conveying of source, or (2) access to copy the Corresponding
269 | Source from a network server at no charge.
270 | - c) Convey individual copies of the object code with a copy of the
271 | written offer to provide the Corresponding Source. This
272 | alternative is allowed only occasionally and noncommercially, and
273 | only if you received the object code with such an offer, in accord
274 | with subsection 6b.
275 | - d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 | - e) Convey the object code using peer-to-peer transmission,
288 | provided you inform other peers where the object code and
289 | Corresponding Source of the work are being offered to the general
290 | public at no charge under subsection 6d.
291 |
292 | A separable portion of the object code, whose source code is excluded
293 | from the Corresponding Source as a System Library, need not be
294 | included in conveying the object code work.
295 |
296 | A "User Product" is either (1) a "consumer product", which means any
297 | tangible personal property which is normally used for personal,
298 | family, or household purposes, or (2) anything designed or sold for
299 | incorporation into a dwelling. In determining whether a product is a
300 | consumer product, doubtful cases shall be resolved in favor of
301 | coverage. For a particular product received by a particular user,
302 | "normally used" refers to a typical or common use of that class of
303 | product, regardless of the status of the particular user or of the way
304 | in which the particular user actually uses, or expects or is expected
305 | to use, the product. A product is a consumer product regardless of
306 | whether the product has substantial commercial, industrial or
307 | non-consumer uses, unless such uses represent the only significant
308 | mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to
312 | install and execute modified versions of a covered work in that User
313 | Product from a modified version of its Corresponding Source. The
314 | information must suffice to ensure that the continued functioning of
315 | the modified object code is in no case prevented or interfered with
316 | solely because modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or
331 | updates for a work that has been modified or installed by the
332 | recipient, or for the User Product in which it has been modified or
333 | installed. Access to a network may be denied when the modification
334 | itself materially and adversely affects the operation of the network
335 | or violates the rules and protocols for communication across the
336 | network.
337 |
338 | Corresponding Source conveyed, and Installation Information provided,
339 | in accord with this section must be in a format that is publicly
340 | documented (and with an implementation available to the public in
341 | source code form), and must require no special password or key for
342 | unpacking, reading or copying.
343 |
344 | ### 7. Additional Terms.
345 |
346 | "Additional permissions" are terms that supplement the terms of this
347 | License by making exceptions from one or more of its conditions.
348 | Additional permissions that are applicable to the entire Program shall
349 | be treated as though they were included in this License, to the extent
350 | that they are valid under applicable law. If additional permissions
351 | apply only to part of the Program, that part may be used separately
352 | under those permissions, but the entire Program remains governed by
353 | this License without regard to the additional permissions.
354 |
355 | When you convey a copy of a covered work, you may at your option
356 | remove any additional permissions from that copy, or from any part of
357 | it. (Additional permissions may be written to require their own
358 | removal in certain cases when you modify the work.) You may place
359 | additional permissions on material, added by you to a covered work,
360 | for which you have or can give appropriate copyright permission.
361 |
362 | Notwithstanding any other provision of this License, for material you
363 | add to a covered work, you may (if authorized by the copyright holders
364 | of that material) supplement the terms of this License with terms:
365 |
366 | - a) Disclaiming warranty or limiting liability differently from the
367 | terms of sections 15 and 16 of this License; or
368 | - b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 | - c) Prohibiting misrepresentation of the origin of that material,
372 | or requiring that modified versions of such material be marked in
373 | reasonable ways as different from the original version; or
374 | - d) Limiting the use for publicity purposes of names of licensors
375 | or authors of the material; or
376 | - e) Declining to grant rights under trademark law for use of some
377 | trade names, trademarks, or service marks; or
378 | - f) Requiring indemnification of licensors and authors of that
379 | material by anyone who conveys the material (or modified versions
380 | of it) with contractual assumptions of liability to the recipient,
381 | for any liability that these contractual assumptions directly
382 | impose on those licensors and authors.
383 |
384 | All other non-permissive additional terms are considered "further
385 | restrictions" within the meaning of section 10. If the Program as you
386 | received it, or any part of it, contains a notice stating that it is
387 | governed by this License along with a term that is a further
388 | restriction, you may remove that term. If a license document contains
389 | a further restriction but permits relicensing or conveying under this
390 | License, you may add to a covered work material governed by the terms
391 | of that license document, provided that the further restriction does
392 | not survive such relicensing or conveying.
393 |
394 | If you add terms to a covered work in accord with this section, you
395 | must place, in the relevant source files, a statement of the
396 | additional terms that apply to those files, or a notice indicating
397 | where to find the applicable terms.
398 |
399 | Additional terms, permissive or non-permissive, may be stated in the
400 | form of a separately written license, or stated as exceptions; the
401 | above requirements apply either way.
402 |
403 | ### 8. Termination.
404 |
405 | You may not propagate or modify a covered work except as expressly
406 | provided under this License. Any attempt otherwise to propagate or
407 | modify it is void, and will automatically terminate your rights under
408 | this License (including any patent licenses granted under the third
409 | paragraph of section 11).
410 |
411 | However, if you cease all violation of this License, then your license
412 | from a particular copyright holder is reinstated (a) provisionally,
413 | unless and until the copyright holder explicitly and finally
414 | terminates your license, and (b) permanently, if the copyright holder
415 | fails to notify you of the violation by some reasonable means prior to
416 | 60 days after the cessation.
417 |
418 | Moreover, your license from a particular copyright holder is
419 | reinstated permanently if the copyright holder notifies you of the
420 | violation by some reasonable means, this is the first time you have
421 | received notice of violation of this License (for any work) from that
422 | copyright holder, and you cure the violation prior to 30 days after
423 | your receipt of the notice.
424 |
425 | Termination of your rights under this section does not terminate the
426 | licenses of parties who have received copies or rights from you under
427 | this License. If your rights have been terminated and not permanently
428 | reinstated, you do not qualify to receive new licenses for the same
429 | material under section 10.
430 |
431 | ### 9. Acceptance Not Required for Having Copies.
432 |
433 | You are not required to accept this License in order to receive or run
434 | a copy of the Program. Ancillary propagation of a covered work
435 | occurring solely as a consequence of using peer-to-peer transmission
436 | to receive a copy likewise does not require acceptance. However,
437 | nothing other than this License grants you permission to propagate or
438 | modify any covered work. These actions infringe copyright if you do
439 | not accept this License. Therefore, by modifying or propagating a
440 | covered work, you indicate your acceptance of this License to do so.
441 |
442 | ### 10. Automatic Licensing of Downstream Recipients.
443 |
444 | Each time you convey a covered work, the recipient automatically
445 | receives a license from the original licensors, to run, modify and
446 | propagate that work, subject to this License. You are not responsible
447 | for enforcing compliance by third parties with this License.
448 |
449 | An "entity transaction" is a transaction transferring control of an
450 | organization, or substantially all assets of one, or subdividing an
451 | organization, or merging organizations. If propagation of a covered
452 | work results from an entity transaction, each party to that
453 | transaction who receives a copy of the work also receives whatever
454 | licenses to the work the party's predecessor in interest had or could
455 | give under the previous paragraph, plus a right to possession of the
456 | Corresponding Source of the work from the predecessor in interest, if
457 | the predecessor has it or can get it with reasonable efforts.
458 |
459 | You may not impose any further restrictions on the exercise of the
460 | rights granted or affirmed under this License. For example, you may
461 | not impose a license fee, royalty, or other charge for exercise of
462 | rights granted under this License, and you may not initiate litigation
463 | (including a cross-claim or counterclaim in a lawsuit) alleging that
464 | any patent claim is infringed by making, using, selling, offering for
465 | sale, or importing the Program or any portion of it.
466 |
467 | ### 11. Patents.
468 |
469 | A "contributor" is a copyright holder who authorizes use under this
470 | License of the Program or a work on which the Program is based. The
471 | work thus licensed is called the contributor's "contributor version".
472 |
473 | A contributor's "essential patent claims" are all patent claims owned
474 | or controlled by the contributor, whether already acquired or
475 | hereafter acquired, that would be infringed by some manner, permitted
476 | by this License, of making, using, or selling its contributor version,
477 | but do not include claims that would be infringed only as a
478 | consequence of further modification of the contributor version. For
479 | purposes of this definition, "control" includes the right to grant
480 | patent sublicenses in a manner consistent with the requirements of
481 | this License.
482 |
483 | Each contributor grants you a non-exclusive, worldwide, royalty-free
484 | patent license under the contributor's essential patent claims, to
485 | make, use, sell, offer for sale, import and otherwise run, modify and
486 | propagate the contents of its contributor version.
487 |
488 | In the following three paragraphs, a "patent license" is any express
489 | agreement or commitment, however denominated, not to enforce a patent
490 | (such as an express permission to practice a patent or covenant not to
491 | sue for patent infringement). To "grant" such a patent license to a
492 | party means to make such an agreement or commitment not to enforce a
493 | patent against the party.
494 |
495 | If you convey a covered work, knowingly relying on a patent license,
496 | and the Corresponding Source of the work is not available for anyone
497 | to copy, free of charge and under the terms of this License, through a
498 | publicly available network server or other readily accessible means,
499 | then you must either (1) cause the Corresponding Source to be so
500 | available, or (2) arrange to deprive yourself of the benefit of the
501 | patent license for this particular work, or (3) arrange, in a manner
502 | consistent with the requirements of this License, to extend the patent
503 | license to downstream recipients. "Knowingly relying" means you have
504 | actual knowledge that, but for the patent license, your conveying the
505 | covered work in a country, or your recipient's use of the covered work
506 | in a country, would infringe one or more identifiable patents in that
507 | country that you have reason to believe are valid.
508 |
509 | If, pursuant to or in connection with a single transaction or
510 | arrangement, you convey, or propagate by procuring conveyance of, a
511 | covered work, and grant a patent license to some of the parties
512 | receiving the covered work authorizing them to use, propagate, modify
513 | or convey a specific copy of the covered work, then the patent license
514 | you grant is automatically extended to all recipients of the covered
515 | work and works based on it.
516 |
517 | A patent license is "discriminatory" if it does not include within the
518 | scope of its coverage, prohibits the exercise of, or is conditioned on
519 | the non-exercise of one or more of the rights that are specifically
520 | granted under this License. You may not convey a covered work if you
521 | are a party to an arrangement with a third party that is in the
522 | business of distributing software, under which you make payment to the
523 | third party based on the extent of your activity of conveying the
524 | work, and under which the third party grants, to any of the parties
525 | who would receive the covered work from you, a discriminatory patent
526 | license (a) in connection with copies of the covered work conveyed by
527 | you (or copies made from those copies), or (b) primarily for and in
528 | connection with specific products or compilations that contain the
529 | covered work, unless you entered into that arrangement, or that patent
530 | license was granted, prior to 28 March 2007.
531 |
532 | Nothing in this License shall be construed as excluding or limiting
533 | any implied license or other defenses to infringement that may
534 | otherwise be available to you under applicable patent law.
535 |
536 | ### 12. No Surrender of Others' Freedom.
537 |
538 | If conditions are imposed on you (whether by court order, agreement or
539 | otherwise) that contradict the conditions of this License, they do not
540 | excuse you from the conditions of this License. If you cannot convey a
541 | covered work so as to satisfy simultaneously your obligations under
542 | this License and any other pertinent obligations, then as a
543 | consequence you may not convey it at all. For example, if you agree to
544 | terms that obligate you to collect a royalty for further conveying
545 | from those to whom you convey the Program, the only way you could
546 | satisfy both those terms and this License would be to refrain entirely
547 | from conveying the Program.
548 |
549 | ### 13. Use with the GNU Affero General Public License.
550 |
551 | Notwithstanding any other provision of this License, you have
552 | permission to link or combine any covered work with a work licensed
553 | under version 3 of the GNU Affero General Public License into a single
554 | combined work, and to convey the resulting work. The terms of this
555 | License will continue to apply to the part which is the covered work,
556 | but the special requirements of the GNU Affero General Public License,
557 | section 13, concerning interaction through a network will apply to the
558 | combination as such.
559 |
560 | ### 14. Revised Versions of this License.
561 |
562 | The Free Software Foundation may publish revised and/or new versions
563 | of the GNU General Public License from time to time. Such new versions
564 | will be similar in spirit to the present version, but may differ in
565 | detail to address new problems or concerns.
566 |
567 | Each version is given a distinguishing version number. If the Program
568 | specifies that a certain numbered version of the GNU General Public
569 | License "or any later version" applies to it, you have the option of
570 | following the terms and conditions either of that numbered version or
571 | of any later version published by the Free Software Foundation. If the
572 | Program does not specify a version number of the GNU General Public
573 | License, you may choose any version ever published by the Free
574 | Software Foundation.
575 |
576 | If the Program specifies that a proxy can decide which future versions
577 | of the GNU General Public License can be used, that proxy's public
578 | statement of acceptance of a version permanently authorizes you to
579 | choose that version for the Program.
580 |
581 | Later license versions may give you additional or different
582 | permissions. However, no additional obligations are imposed on any
583 | author or copyright holder as a result of your choosing to follow a
584 | later version.
585 |
586 | ### 15. Disclaimer of Warranty.
587 |
588 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
589 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
590 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT
591 | WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT
592 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
593 | A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND
594 | PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE
595 | DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
596 | CORRECTION.
597 |
598 | ### 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR
602 | CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
603 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES
604 | ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT
605 | NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR
606 | LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM
607 | TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER
608 | PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
609 |
610 | ### 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | ## How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these
626 | terms.
627 |
628 | To do so, attach the following notices to the program. It is safest to
629 | attach them to the start of each source file to most effectively state
630 | the exclusion of warranty; and each file should have at least the
631 | "copyright" line and a pointer to where the full notice is found.
632 |
633 |
634 | Copyright (C)
635 |
636 | This program is free software: you can redistribute it and/or modify
637 | it under the terms of the GNU General Public License as published by
638 | the Free Software Foundation, either version 3 of the License, or
639 | (at your option) any later version.
640 |
641 | This program is distributed in the hope that it will be useful,
642 | but WITHOUT ANY WARRANTY; without even the implied warranty of
643 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
644 | GNU General Public License for more details.
645 |
646 | You should have received a copy of the GNU General Public License
647 | along with this program. If not, see .
648 |
649 | Also add information on how to contact you by electronic and paper
650 | mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands \`show w' and \`show c' should show the
661 | appropriate parts of the General Public License. Of course, your
662 | program's commands might be different; for a GUI interface, you would
663 | use an "about box".
664 |
665 | You should also get your employer (if you work as a programmer) or
666 | school, if any, to sign a "copyright disclaimer" for the program, if
667 | necessary. For more information on this, and how to apply and follow
668 | the GNU GPL, see .
669 |
670 | The GNU General Public License does not permit incorporating your
671 | program into proprietary programs. If your program is a subroutine
672 | library, you may consider it more useful to permit linking proprietary
673 | applications with the library. If this is what you want to do, use the
674 | GNU Lesser General Public License instead of this License. But first,
675 | please read .
676 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | all:
2 | dune build
3 |
4 | run:
5 | dune exec sql
6 |
7 | clean:
8 | rm -rf _build
9 | rm -rf release
10 |
11 | dist:
12 | dune install --prefix=release
13 | tar -zcvf sqlc.tar.gz release
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # sqlc
2 |
3 | > [!WARNING]
4 | > THIS PROJECT IS EXPIRIMENTAL AND SHOULD NOT BE USED IN PRODUCTION
5 |
6 | sqlc is a basic SQL statement parser and executor written in OCaml. It provides a simple and efficient way to parse and execute SQL statements.
7 |
8 | It uses csv files as tables, and directories as databases.
9 |
10 | ## Features
11 |
12 | - **SQL Parsing**: sqlc can parse a simple range of SQL statements, including SELECT, INSERT, UPDATE, DELETE, and more.
13 | - **Query Execution**: sqlc provides a basic query execution engine that can execute SQL statements against a database.
14 |
15 | ### Supported Statements
16 |
17 | sqlc currently supports the following SQL statements:
18 |
19 | - `SELECT column1, column2, ... FROM IDENTIFIER [ WHERE condition ];`
20 | - `CREATE DATABASE IDENTIFIER;`
21 | - `USE DATABASE IDENTIFIER;`
22 | - `CREATE TABLE IDENTIFIER ( table_columns );`
23 | - `SHOW TABLES;`
24 | - `SHOW DATABASES;`
25 | - `INSERT INTO IDENTIFIER ( column1, column2, ... ) VALUES ( value1, value2, ... ) [ ( value1, value2, ... ) ... ];`
26 | - `UPDATE IDENTIFIER SET IDENTIFIER EQUALS value [ WHERE condition ];`
27 | - `DELETE FROM IDENTIFIER [ WHERE condition ];`
28 | - `DROP TABLE IDENTIFIER;`
29 | - `DROP DATABASE IDENTIFIER;`
30 | - `EXIT;`
31 |
32 | The condition is a simple expression that can include logical operators (`AND`, `OR`, `NOT`), comparison operators (`=`, `<>`, `>`, `<`, `>=`, `<=`), and parentheses.
33 |
34 | ## Getting Started
35 |
36 | To get started with sqlc, follow these steps:
37 |
38 | 1. Install OCaml on your system.
39 | 2. Clone the sqlc repository.
40 | 3. Build the project using the provided build script.
41 | 4. Start using sqlc.
42 |
43 | Or download from the release page.
44 |
45 | For more detailed instructions, please refer to the [Installation Guide](./docs/installation.md) in the project documentation.
46 |
47 | ## Contributing
48 |
49 | Contributions to sqlc are welcome! If you would like to contribute, please follow the guidelines outlined in the [Contributing Guide](./CONTRIBUTING.md).
50 |
51 | ## License
52 |
53 | sqlc is licensed under the GNU General Public License v3.0. For more information, please refer to the [LICENSE](./LICENSE) file.
54 |
--------------------------------------------------------------------------------
/TODO.md:
--------------------------------------------------------------------------------
1 | - [x]支持INSERT后跟随多个VALUES
2 | - [x]插入类型验证
3 | - [ ]交互tab补全&方向键移动+历史命令
4 | - [ ]多行sql语句
5 | - [ ]注释
6 | - [x]无头模式执行sql文件
7 | - [ ]多表join查询
8 | - [ ]索引功能
9 | - [ ]视图功能
10 | - [ ]提供用于web后端能力的标准库
11 | - [ ]文件i/o
12 | - [ ]http api库
13 | - [ ]json序列化/反序列化支持
14 | - [ ]yaml配置解析
15 | - [ ]more modern sql with variables & http server & io support & more
--------------------------------------------------------------------------------
/docs/installation.md:
--------------------------------------------------------------------------------
1 | # Installation
2 |
3 | ## Binary Installation
4 |
5 | You can download the pre-built binary from the GitHub releases page.
6 |
7 | ## Source Code Installation
8 |
9 | To install from source code, follow these steps:
10 |
11 | Ensure the following dependencies are installed on your system:
12 |
13 | - OCaml 5.0 or later
14 | - OPAM 2.0 or later
15 | - GNU Make 4.0 or later
16 |
17 | 1. Clone the repository from GitHub using the command `git clone https://github.com/xeonds/sqlc`
18 | 2. Navigate to the cloned repository directory using the command `cd sqlc`
19 | 3. Run the command `make sql` to compile the SQL parser.
20 |
21 | Once the build is complete, you can see the compiled binary at `./sql`.
22 |
23 | ## System Requirements
24 |
25 | Before installing the software, make sure your system meets the following requirements:
26 |
27 | - Operating System: Windows 10, macOS 10.14 or later, or Linux (Ubuntu 20.04 or later)
28 | - Processor: Intel Core i5 or equivalent
29 | - Memory: 512MB RAM
30 | - Storage: 256MB of free disk space
31 |
32 | ## Troubleshooting
33 |
34 | If you encounter any issues during the software running process, please check the following:
35 |
36 | - Ensure that all dependencies are installed correctly.
37 | - Verify that the software is compatible with your operating system.
38 | - Check the system logs for any error messages that may indicate the cause of the issue.
39 |
40 | If the issue persists, please open an issue on the GitHub repository and provide as much information as possible to help us resolve the problem.
41 |
--------------------------------------------------------------------------------
/dune-project:
--------------------------------------------------------------------------------
1 | (lang dune 3.16)
2 |
3 | (name sqlc)
4 |
5 | (source
6 | (github xeonds/sqlc))
7 |
8 | (authors "xeonds")
9 |
10 | (maintainers "Maintainer Name")
11 |
12 | (license GPL-3.0)
13 |
14 | (documentation https://github.com/xeonds/sqlc)
15 |
16 | (package
17 | (name sqlc)
18 | (synopsis "A SQL compiler")
19 | (description "A SQL compiler")
20 | (depends ocaml dune csv angstrom)
21 | (tags
22 | (topics sql)))
23 |
--------------------------------------------------------------------------------
/src/README.md:
--------------------------------------------------------------------------------
1 | # sqlc
2 |
3 | ## http_engine
4 |
5 | provide stdlib for:
6 |
7 | - request path & type mapper
8 | - request handler with sql-ex lang
9 | - json support
10 |
11 | the http-lib should run at backend, when executed the part, just open a thread at backend to handle requests, until the main process(repl engine or executor process) exited.
12 |
13 | and it will show logs to stdout when handle request, and can be set to be silent.
14 |
15 | also, support interactions with other stdlib components, like run sql from http content using db_engine,
16 | storage content to filesystem, and string process using io_engine, data manipulation using data_engine, etc.
17 |
18 | ## db_engine
19 |
20 | provides stdlib for:
21 |
22 | - sql engine for csv database operation
23 |
24 | this part is standard sql database support, supporting acid actions and some dbms features
25 |
26 | now I'm planning support higher query process like join, groupby, etc., and core features
27 | like transactions, views, permission control.
28 |
29 | ## io_engine
30 |
31 | provides stdlib for:
32 |
33 | - file i/o of system
34 | - string process lib
35 |
36 | support file i/o, string process, and auto-serialize of data types. user can serialize data to
37 |
38 | ## data_engine
39 |
40 | provides stdlib for:
41 |
42 | - array operations
43 | - basic data types
44 | - user-defined compose data types
45 |
46 | ## main
47 |
48 | entrance of program, supports interactive mode or headless mode(read command from file)
49 |
50 | ## ast
51 |
52 | language statements & expressions & data types defination
53 |
54 | ## parser&lexer
55 |
56 | language words & language statements parser
57 |
--------------------------------------------------------------------------------
/src/data_engine.ml:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xeonds/sqlc/90ba3df2f14c31edd1a8888adb76e81b3384961b/src/data_engine.ml
--------------------------------------------------------------------------------
/src/db_engine.ml:
--------------------------------------------------------------------------------
1 | module Types = struct
2 | type dtype = String | Int | Bool | Float
3 | type value = VString of string | VInt of int | VBool of bool | VFloat of float
4 |
5 | let cast_value dtype value =
6 | match dtype with
7 | | String -> VString value
8 | | Int -> VInt (int_of_string value)
9 | | Bool -> VBool (bool_of_string value)
10 | | Float -> VFloat (float_of_string value)
11 |
12 | let cast_type = function
13 | | String -> "string"
14 | | Int -> "int"
15 | | Bool -> "bool"
16 | | Float -> "float"
17 |
18 | let type_of_string = function
19 | | "string" -> String
20 | | "int" -> Int
21 | | "bool" -> Bool
22 | | "float" -> Float
23 | | _ -> failwith "Invalid type"
24 |
25 | let string_of_value = function
26 | | VString s -> s
27 | | VInt i -> string_of_int i
28 | | VBool b -> string_of_bool b
29 | | VFloat f -> string_of_float f
30 |
31 | let default_value = function
32 | | String -> VString ""
33 | | Int -> VInt 0
34 | | Bool -> VBool false
35 | | Float -> VFloat 0.0
36 |
37 | type field_spec = {
38 | name : string;
39 | dtype : dtype;
40 | }
41 |
42 | type table = {
43 | schema : field_spec list;
44 | mutable data : value list list;
45 | path : string;
46 | }
47 |
48 | type expr =
49 | | Literal of value
50 | | Column of string
51 | | BinOp of expr * string * expr
52 | | Call of string * expr list
53 |
54 | type statement =
55 | | Select of string list * string * (string * expr) option * expr option
56 | | CreateTable of string * (string * dtype) list
57 | | InsertInto of string * string list * value list list
58 | | Update of string * string * value * expr option
59 | | DeleteFrom of string * expr option
60 | | ShowTables
61 | | DropTable of string
62 | | LoadObject of expr
63 | | StoreObject of expr
64 | | Exit
65 |
66 | type eval =
67 | | Select of string list * table * expr option
68 | | Join of table * table * expr
69 | | CreateTable of string * (string * dtype) list
70 | | InsertInto of table * string list * value list list
71 | | Update of table * string * value * expr option
72 | | DeleteFrom of table * expr option
73 | | ShowTables
74 | | DropTable of string
75 | | LoadObject of expr
76 | | StoreObject of expr
77 | | Exit
78 |
79 | let string_of_table tbl =
80 | let header = List.map (fun f -> f.name ^ ":" ^ cast_type f.dtype) tbl.schema |> String.concat "," in
81 | let rows = List.map (fun row ->
82 | List.map string_of_value row |> String.concat ","
83 | ) tbl.data |> String.concat "\n" in
84 | header ^ "\n" ^ rows
85 | end
86 |
87 | module Database = struct
88 | open Types
89 |
90 | let init_db db_name =
91 | if Sys.file_exists db_name then
92 | failwith "Database already exists"
93 | else
94 | Unix.mkdir db_name 0o777
95 |
96 | let load_table path =
97 | let ic = open_in path in
98 | let schema =
99 | input_line ic
100 | |> String.split_on_char ','
101 | |> List.map (fun s ->
102 | match String.split_on_char ':' s with
103 | | [name; "string"] -> {name; dtype=String}
104 | | [name; "int"] -> {name; dtype=Int}
105 | | [name; "bool"] -> {name; dtype=Bool}
106 | | [name; "float"] -> {name; dtype=Float}
107 | | _ -> failwith "Invalid header format")
108 | in
109 | let data =
110 | let rec read_lines acc =
111 | try
112 | let line = input_line ic |> String.split_on_char ',' in
113 | let row = List.map2 (fun f v -> cast_value f.dtype v) schema line in
114 | read_lines (row::acc)
115 | with End_of_file -> List.rev acc
116 | in
117 | read_lines []
118 | in
119 | close_in ic;
120 | {schema; data; path}
121 |
122 | let save_table tbl =
123 | let oc = open_out tbl.path in
124 | let schema_str = List.map (fun f -> f.name ^ ":" ^ cast_type f.dtype) tbl.schema |> String.concat "," in
125 | output_string oc (schema_str ^ "\n");
126 | List.iter (fun row ->
127 | let line = List.map (function
128 | | VString s -> s
129 | | VInt i -> string_of_int i
130 | | VBool b -> string_of_bool b
131 | | VFloat f -> string_of_float f)
132 | row
133 | |> String.concat ","
134 | in
135 | output_string oc (line ^ "\n")
136 | ) tbl.data;
137 | close_out oc
138 |
139 | (* append new line in memory *)
140 | (* need manual writeback *)
141 | let append_row tbl (row: value list) =
142 | if List.length row <> List.length tbl.schema then
143 | failwith "Row length does not match table schema"
144 | else
145 | (* check if each item's type in row matches the corresponding position's tbl.scheme's type *)
146 | List.iter2 (fun f v ->
147 | match f.dtype, v with
148 | | String, VString _ | Int, VInt _ | Bool, VBool _ | Float, VFloat _ -> ()
149 | | _ -> failwith "Type mismatch") tbl.schema row;
150 | tbl.data <- row::tbl.data
151 | end
152 |
153 | module ObjectStorage = struct
154 | let hash_content data =
155 | Digest.string data |> Digest.to_hex
156 |
157 | (* hash filename & storage it to folder *)
158 | let store_file ~user_dir filename content =
159 | let hash_name = hash_content filename in
160 | let object_path = Filename.concat user_dir hash_name in
161 | let oc = open_out_bin object_path in
162 | output_string oc content;
163 | close_out oc;
164 | hash_name
165 |
166 | let retrieve_file ~user_dir hash =
167 | let path = Filename.concat user_dir hash in
168 | if Sys.file_exists path then
169 | let ic = open_in_bin path in
170 | let content = really_input_string ic (in_channel_length ic) in
171 | close_in ic;
172 | Some content
173 | else None
174 | end
175 |
176 | module Engine = struct
177 | open Types
178 |
179 | (* expr evaluate *)
180 | let eval_cond cond row field_specs =
181 | let rec eval_expr = function
182 | | Literal v -> v
183 | | Column name -> List.assoc name (List.combine (List.map (fun f -> f.name) field_specs) row)
184 | | BinOp (e1, op, e2) -> (
185 | let v1 = eval_expr e1 in
186 | let v2 = eval_expr e2 in
187 | match op with
188 | | "+" -> (match v1, v2 with
189 | | VInt i1, VInt i2 -> VInt (i1 + i2)
190 | | VFloat f1, VFloat f2 -> VFloat (f1 +. f2)
191 | | _ -> failwith "Type mismatch")
192 | | "-" -> (match v1, v2 with
193 | | VInt i1, VInt i2 -> VInt (i1 - i2)
194 | | VFloat f1, VFloat f2 -> VFloat (f1 -. f2)
195 | | _ -> failwith "Type mismatch")
196 | | "*" -> (match v1, v2 with
197 | | VInt i1, VInt i2 -> VInt (i1 * i2)
198 | | VFloat f1, VFloat f2 -> VFloat (f1 *. f2)
199 | | _ -> failwith "Type mismatch")
200 | | "/" -> (match v1, v2 with
201 | | VInt i1, VInt i2 -> VInt (i1 / i2)
202 | | VFloat f1, VFloat f2 -> VFloat (f1 /. f2)
203 | | _ -> failwith "Type mismatch")
204 | | "%" -> (match v1, v2 with
205 | | VInt i1, VInt i2 -> VInt (i1 mod i2)
206 | | _ -> failwith "Type mismatch")
207 | | "=" -> (match v1, v2 with
208 | | VInt i1, VInt i2 -> VBool (i1 = i2)
209 | | VFloat f1, VFloat f2 -> VBool (f1 = f2)
210 | | VBool b1, VBool b2 -> VBool (b1 = b2)
211 | | VString s1, VString s2 -> VBool (s1 = s2)
212 | | _ -> failwith "Type mismatch")
213 | | "<" -> (match v1, v2 with
214 | | VInt i1, VInt i2 -> VBool (i1 < i2)
215 | | VFloat f1, VFloat f2 -> VBool (f1 < f2)
216 | | _ -> failwith "Type mismatch")
217 | | ">" -> (match v1, v2 with
218 | | VInt i1, VInt i2 -> VBool (i1 > i2)
219 | | VFloat f1, VFloat f2 -> VBool (f1 > f2)
220 | | _ -> failwith "Type mismatch")
221 | | "<=" -> (match v1, v2 with
222 | | VInt i1, VInt i2 -> VBool (i1 <= i2)
223 | | VFloat f1, VFloat f2 -> VBool (f1 <= f2)
224 | | _ -> failwith "Type mismatch")
225 | | ">=" -> (match v1, v2 with
226 | | VInt i1, VInt i2 -> VBool (i1 >= i2)
227 | | VFloat f1, VFloat f2 -> VBool (f1 >= f2)
228 | | _ -> failwith "Type mismatch")
229 | | "<>" | "!=" -> (match v1, v2 with
230 | | VInt i1, VInt i2 -> VBool (i1 <> i2)
231 | | VFloat f1, VFloat f2 -> VBool (f1 <> f2)
232 | | VBool b1, VBool b2 -> VBool (b1 <> b2)
233 | | VString s1, VString s2 -> VBool (s1 <> s2)
234 | | _ -> failwith "Type mismatch")
235 | | "AND" -> (match v1, v2 with
236 | | VBool b1, VBool b2 -> VBool (b1 && b2)
237 | | _ -> failwith "Type mismatch")
238 | | "OR" -> (match v1, v2 with
239 | | VBool b1, VBool b2 -> VBool (b1 || b2)
240 | | _ -> failwith "Type mismatch")
241 | | _ -> failwith "Unsupported operator")
242 | | Call (name, args) -> (
243 | match name with
244 | | "if" -> (match args with
245 | | [cond; e1; e2] -> (match eval_expr cond with
246 | | VBool true -> eval_expr e1
247 | | VBool false -> eval_expr e2
248 | | _ -> failwith "Type mismatch")
249 | | _ -> failwith "Invalid number of arguments")
250 | | "not" -> (match args with
251 | | [e] -> (match eval_expr e with
252 | | VBool b -> VBool (not b)
253 | | _ -> failwith "Type mismatch")
254 | | _ -> failwith "Invalid number of arguments")
255 | | _ -> failwith "Unsupported function")
256 | in
257 | eval_expr cond |> function
258 | | VBool b -> b
259 | | _ -> failwith "Type mismatch"
260 |
261 | (** 执行查询语句返回结果表 *)
262 | let execute = function
263 | | Select (cols, table, where) ->
264 | let rows = match where with
265 | | None -> table.data
266 | | Some cond -> List.filter (fun row -> eval_cond cond row table.schema) table.data in
267 | let filtered =
268 | if List.mem "*" cols then rows
269 | else
270 | List.map (fun row -> List.map (fun col -> List.assoc col (List.combine (List.map (fun f -> f.name) table.schema) row)) cols) rows in
271 | {table with data=filtered}
272 | | Join (left, right, on) ->
273 | let left_col, right_col = match on with
274 | | BinOp (Column c, "=", Column c') when List.mem c (List.map (fun f -> f.name) left.schema) && List.mem c' (List.map (fun f -> f.name) right.schema) -> c, c'
275 | | _ -> failwith "Invalid join condition" in
276 | let left_index = List.assoc left_col (List.mapi (fun i f -> (f.name, i)) left.schema) in
277 | let right_index = List.assoc right_col (List.mapi (fun i f -> (f.name, i)) right.schema) in
278 | let right_map = List.fold_left (fun acc row ->
279 | let key = List.nth row right_index in
280 | let values = try List.assoc key acc with Not_found -> [] in
281 | (key, row :: values) :: List.remove_assoc key acc) [] right.data in
282 | let joined = List.fold_left (fun acc row1 ->
283 | let key = List.nth row1 left_index in
284 | match List.assoc_opt key right_map with
285 | | Some rows2 -> List.rev_append (List.map (fun row2 -> row1 @ row2) rows2) acc
286 | | None -> acc) [] left.data in
287 | {schema=left.schema @ right.schema; data=List.rev joined; path = ""}
288 | | CreateTable (name, cols) ->
289 | let table_path = name ^ ".csv" in
290 | if Sys.file_exists table_path then
291 | failwith "Table already exists"
292 | else
293 | let schema = List.map (fun (name, dtype) -> {name; dtype}) cols in
294 | let tbl = {schema; data=[]; path=table_path} in
295 | Database.save_table tbl;
296 | tbl
297 | | ShowTables ->
298 | let rec print_tree path prefix =
299 | let entries = Sys.readdir path |> Array.to_list |> List.sort String.compare in
300 | List.iteri (fun i entry ->
301 | let is_last = i = List.length entries - 1 in
302 | let new_prefix = prefix ^ (if is_last then "└── " else "├── ") in
303 | let full_path = Filename.concat path entry in
304 | if Sys.is_directory full_path then begin
305 | Printf.printf "%s%s/\n" new_prefix entry;
306 | print_tree full_path (prefix ^ (if is_last then " " else "│ "))
307 | end else if Filename.check_suffix entry ".csv" then begin
308 | let ic = open_in full_path in
309 | let first_row = try input_line ic with End_of_file -> "" in
310 | let line_count = ref 0 in
311 | try while true do ignore (input_line ic); incr line_count done
312 | with End_of_file -> close_in ic;
313 | Printf.printf "%s%s (First row: %s, Lines: %d)\n" new_prefix entry first_row !line_count
314 | end else
315 | Printf.printf "%s%s\n" new_prefix entry
316 | ) entries
317 | in
318 | print_tree "." "";
319 | {schema=[]; data=[]; path=""}
320 | | InsertInto (table, cols, vals) ->
321 | let rows = List.map (fun row ->
322 | List.map (fun f ->
323 | match List.assoc_opt f.name (List.combine cols row) with
324 | | Some v -> v
325 | | None -> default_value f.dtype
326 | ) table.schema
327 | ) vals in
328 | List.iter (fun row -> Database.append_row table row) rows;
329 | table
330 | | Update (table, col, value, cond) ->
331 | let col_index = List.assoc col (List.mapi (fun i f -> (f.name, i)) table.schema) in
332 | let data_updated = List.map (fun row ->
333 | if (match cond with
334 | | None -> true
335 | | Some c -> eval_cond c row table.schema) then
336 | List.mapi (fun i v -> if i == col_index then value else v) row else row
337 | ) table.data in
338 | table.data <- data_updated;
339 | table
340 | | DeleteFrom (table, cond) ->
341 | let data_deleted = List.filter (fun row -> match cond with
342 | | None -> true
343 | | Some c -> not (eval_cond c row table.schema)) table.data in
344 | table.data <- data_deleted;
345 | table
346 | | DropTable name ->
347 | Sys.remove name;
348 | {schema=[]; data=[]; path=name}
349 | | LoadObject expr ->
350 | (* placeholder, don't use *)
351 | let path = match expr with
352 | | Literal (VString s) -> s
353 | | _ -> failwith "Invalid argument" in
354 | let content = ObjectStorage.retrieve_file ~user_dir:"." path in
355 | (match content with
356 | | Some data ->
357 | let tbl = Database.load_table data in
358 | tbl
359 | | None -> failwith "Object not found")
360 | | StoreObject expr ->
361 | (* placeholder, don't use *)
362 | let tbl = match expr with
363 | | Literal (VString s) -> Database.load_table s
364 | | _ -> failwith "Invalid argument" in
365 | let path = ObjectStorage.store_file ~user_dir:"." tbl.path (tbl.path ^ ".csv") in
366 | Database.append_row tbl [VString path];
367 | Database.save_table tbl;
368 | tbl
369 | | Exit -> exit 0
370 | end
371 |
--------------------------------------------------------------------------------
/src/dune:
--------------------------------------------------------------------------------
1 | (executable
2 | (name main)
3 | (public_name sql)
4 | (modules main http_engine db_engine lexer parser)
5 | (libraries angstrom csv unix cmdliner lwt.unix cohttp cohttp-lwt-unix yojson lwt_ppx)
6 | (preprocess (pps lwt_ppx)))
7 |
8 | (ocamllex lexer)
9 | (ocamlyacc parser)
--------------------------------------------------------------------------------
/src/http_engine.ml:
--------------------------------------------------------------------------------
1 | module Web = struct
2 | open Lwt
3 | open Cohttp
4 | open Cohttp_lwt_unix
5 | open Lwt.Syntax
6 |
7 | (* 请求数据类型 *)
8 | type request_data =
9 | | JSON of Yojson.Safe.t
10 | | Text of string
11 | | FormFile of (string * string) list (* (字段名, 临时路径) *)
12 | | Binary of string
13 |
14 | (* 响应数据类型 *)
15 | type response_data =
16 | | JsonResponse of Yojson.Safe.t
17 | | TextResponse of string
18 | | FileResponse of string (* 文件路径 *)
19 | | BinaryResponse of bytes
20 |
21 | (* RESTful路由类型 *)
22 | type route_pattern =
23 | | Static of string
24 | | Dynamic of string (* :id形式 *)
25 | | Wildcard
26 |
27 | type route = {
28 | method_: Code.meth;
29 | path: route_pattern list;
30 | handler: ((string * string)list -> request_data -> response_data Lwt.t);
31 | }
32 |
33 | (* Web服务状态 *)
34 | type service = {
35 | routes: route list ref;
36 | mutable middlewares: (Request.t -> request_data -> (Request.t * request_data) Lwt.t) list;
37 | }
38 |
39 | (* 路由解析器:路径串 string 转 route_pattern list *)
40 | let parse_path path =
41 | let split = path |> Uri.path
42 | |> String.split_on_char '/'
43 | |> List.filter (fun s -> s <> "") in
44 | List.map (fun s ->
45 | match s.[0] with
46 | | ':' -> Dynamic (String.sub s 1 (String.length s - 1))
47 | | '*' -> Wildcard
48 | | _ -> Static s
49 | ) split
50 |
51 | (* 路由匹配,在所有 pattern 中找到匹配请求 path 的 pattern *)
52 | let rec match_route pattern path =
53 | match (pattern, path) with
54 | | [], [] -> Some []
55 | | Wildcard::_, _ -> Some []
56 | | Dynamic name::pt, Static hd::phd ->
57 | (* 匹配该动态域之后的部分是否有其他参数,将它们跟在该字段后返回 *)
58 | (match match_route pt phd with
59 | | Some params -> Some ((name, hd)::params)
60 | | None -> None)
61 | | Static a::pt, Static b::phd when a = b -> match_route pt phd
62 | | _ -> None
63 |
64 | (* 请求处理器 *)
65 | let handle_request service req body =
66 | let parse_multipart req body =
67 | let open Cohttp_lwt.Body in
68 | let%lwt body = to_string body in
69 | let boundary = req |> Request.headers |> fun h -> Header.get h "content-type" |> Option.get in
70 | let boundary = String.split_on_char '=' boundary |> List.tl |> String.concat "=" in
71 | let boundary = "--" ^ boundary in
72 | let parts = Re.Str.(split (regexp_string boundary) body) in
73 | let parts = List.filter (fun s -> s <> "" && s <> "--") parts in
74 | let parse_part part =
75 | let lines = String.split_on_char '\n' part in
76 | let lines = List.filter (fun s -> s <> "") lines in
77 | let header = List.hd lines in
78 | let header = String.split_on_char ';' header in
79 | let header = List.map (fun s -> String.trim s) header in
80 | let header = List.map (fun s -> String.split_on_char '=' s) header in
81 | let header = List.filter_map (function
82 | | [k; v] -> Some (k, v)
83 | | _ -> None
84 | ) header in
85 | let header = List.to_seq header |> Hashtbl.of_seq in
86 | let content = List.tl lines |> String.concat "\n" in
87 | let name = Hashtbl.find header "name" in
88 | let filename = Hashtbl.find_opt header "filename" in
89 | match filename with
90 | | Some _filename ->
91 | let tmp_path = Filename.temp_file "upload" "tmp" in
92 | Lwt_io.with_file ~mode:Lwt_io.output tmp_path (fun oc -> Lwt_io.write oc content)
93 | >|= fun () -> (name, tmp_path)
94 | | None -> Lwt.return (name, content)
95 | in
96 | Lwt_list.map_p parse_part parts
97 | in
98 | let path = req |> Request.uri in
99 | let meth = req |> Request.meth in
100 | let%lwt req_data =
101 | match Request.headers req |> Header.get_media_type with
102 | | Some "application/json" ->
103 | body |> Cohttp_lwt.Body.to_string >|= Yojson.Safe.from_string >|= fun j -> JSON j
104 | | Some "text/plain" ->
105 | body |> Cohttp_lwt.Body.to_string >|= fun s -> Text s
106 | | Some "multipart/form-data" ->
107 | (* 实现文件上传解析 *)
108 | parse_multipart req body >|= fun files -> FormFile files
109 | | _ ->
110 | body |> Cohttp_lwt.Body.to_string >|= fun s -> Text s
111 | in
112 |
113 | (* 应用中间件 *)
114 | (* TODO: 给请求参数叠进去 *)
115 | let%lwt (req, req_data) =
116 | List.fold_left (fun acc m -> acc >>= fun (r, d) -> m r d)
117 | (Lwt.return (req, req_data)) service.middlewares
118 | in
119 |
120 | (* 查找匹配路由 *)
121 | let matched = List.find_opt (fun r ->
122 | r.method_ = meth &&
123 | match match_route r.path (parse_path path) with
124 | | Some _ -> true
125 | | None -> false
126 | ) !(service.routes) in
127 |
128 | match matched with
129 | | Some route ->
130 | let params = match_route route.path (parse_path path) |> Option.get in
131 | let%lwt resp = route.handler params req_data in
132 | (match resp with
133 | | JsonResponse j ->
134 | let body = Yojson.Safe.to_string j |> Cohttp_lwt.Body.of_string in
135 | Server.respond ~status:`OK ~headers:(Header.init_with "Content-Type" "application/json") ~body ()
136 | | TextResponse t ->
137 | Server.respond_string ~headers:(Header.init_with "Content-Type" "text/plain") ~status:`OK ~body:t ()
138 | | FileResponse path ->
139 | let%lwt body = Lwt_io.(with_file ~mode:input path read) >|= Cohttp_lwt.Body.of_string in
140 | let mime_type path =
141 | match Filename.extension path with
142 | | ".html" -> "text/html"
143 | | ".css" -> "text/css"
144 | | ".js" -> "application/javascript"
145 | | ".json" -> "application/json"
146 | | ".png" -> "image/png"
147 | | ".jpg" | ".jpeg" -> "image/jpeg"
148 | | ".gif" -> "image/gif"
149 | | _ -> "application/octet-stream"
150 | in
151 | Server.respond ~status:`OK ~headers:(Header.init_with "Content-Type" (mime_type path)) ~body ()
152 | | BinaryResponse b ->
153 | Server.respond ~headers:(Header.init_with "Content-Type" "application/octet-stream")
154 | ~body:(Cohttp_lwt.Body.of_string (Bytes.to_string b)) ~status:`OK ())
155 | | None ->
156 | Server.respond_string ~status:`Not_found ~body:"Route not found" ()
157 |
158 | (* RESTful路由注册 *)
159 | let add_route service meth path handler =
160 | let pattern = parse_path (Uri.of_string path) in
161 | service.routes := {method_=meth; path=pattern; handler} :: !(service.routes)
162 |
163 | (* 中间件系统 *)
164 | let add_middleware service middleware =
165 | service.middlewares <- middleware :: service.middlewares
166 |
167 | (* 日志中间件 *)
168 | let logging_middleware req data =
169 | let%lwt () = Logs_lwt.info (fun m -> m "Request: %s %s"
170 | (Code.string_of_method req.Request.meth)
171 | (Request.uri req |> Uri.path)) in
172 | Lwt.return (req, data)
173 |
174 | (* CORS中间件 *)
175 | let cors_middleware req data =
176 | let headers = Header.init_with "Access-Control-Allow-Origin" "*"
177 | |> fun h -> Header.add h "Access-Control-Allow-Methods" "GET, POST, PUT, DELETE, OPTIONS"
178 | |> fun h -> Header.add h "Access-Control-Allow-Headers" "Content-Type" in
179 | Lwt.return (req, data)
180 |
181 | (* 服务创建 *)
182 |
183 | (* 启动服务 *)
184 | let start service port =
185 | let callback _conn req body =
186 | handle_request service req body
187 | in
188 | Server.create ~mode:(`TCP (`Port port)) (Server.make ~callback ())
189 | end
190 |
--------------------------------------------------------------------------------
/src/io_engine.ml:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xeonds/sqlc/90ba3df2f14c31edd1a8888adb76e81b3384961b/src/io_engine.ml
--------------------------------------------------------------------------------
/src/lexer.mll:
--------------------------------------------------------------------------------
1 | {
2 | open Parser
3 |
4 | exception Lexing_error of string
5 | }
6 |
7 | let whitespace = [' ' '\t' '\n' '\r']+
8 | let digit = ['0'-'9']
9 | let alpha = ['a'-'z' 'A'-'Z']
10 | let alphanum = alpha | digit
11 |
12 | rule token = parse
13 | | whitespace { token lexbuf } (* Ignore whitespace *)
14 | | digit+ as num { INT (int_of_string num) }
15 | | digit+ "." digit* as num { FLOAT (float_of_string num) }
16 | | (alpha | '_') (alphanum | '_')* as id {
17 | match String.lowercase_ascii id with
18 | | "create" -> CREATE
19 | | "use" -> USE
20 | | "show" -> SHOW
21 | | "insert" -> INSERT
22 | | "into" -> INTO
23 | | "select" -> SELECT
24 | | "update" -> UPDATE
25 | | "set" -> SET
26 | | "drop" -> DROP
27 | | "delete" -> DELETE
28 | | "from" -> FROM
29 | | "where" -> WHERE
30 | | "exit" -> EXIT
31 | | "database" -> DATABASE
32 | | "databases" -> DATABASES
33 | | "tables" -> TABLES
34 | | "table" -> TABLE
35 | | "values" -> VALUES
36 | | "join" -> JOIN
37 | | "on" -> ON
38 | | "as" -> AS
39 | | "order" -> ORDER
40 | | "begin" -> BEGIN
41 | | "transaction" -> TRANSACTION
42 | | "commit" -> COMMIT
43 | | "rollback" -> ROLLBACK
44 | | "lock" -> LOCK
45 | | "unlock" -> UNLOCK
46 | | "view" -> VIEW
47 | | "index" -> INDEX
48 | | "log" -> LOG
49 | | "int" -> INT_TYPE
50 | | "string" -> STRING_TYPE
51 | | "float" -> FLOAT_TYPE
52 | | "bool" -> BOOL_TYPE
53 | | "and" -> AND
54 | | "or" -> OR
55 | | "not" -> NOT
56 | | "true" -> BOOL true
57 | | "false" -> BOOL false
58 | | _ -> IDENTIFIER id
59 | }
60 | | ['a'-'z' 'A'-'Z' '0'-'9' '/' '.' '_']+ as path { FILE path }
61 | | '"'[^'"']*'"' as str { STRING (String.sub str 1 (String.length str - 2)) }
62 | | "*" { STAR }
63 | | "," { COMMA }
64 | | ";" { SEMICOLON }
65 | | "." { DOT }
66 | | "=" { EQUALS }
67 | | "<" { LESS }
68 | | ">" { GREATER }
69 | | "<=" { LESS_EQUAL }
70 | | ">=" { GREATER_EQUAL }
71 | | "<>" { NOT_EQUAL }
72 | | "+" { PLUS }
73 | | "-" { MINUS }
74 | | "/" { DIVIDE }
75 | | "%" { MOD }
76 | | "(" { LPAREN }
77 | | ")" { RPAREN }
78 | | eof { EOF }
79 | | _ as c { raise (Lexing_error (Printf.sprintf "Unexpected character: %c" c)) }
80 |
--------------------------------------------------------------------------------
/src/main.ml:
--------------------------------------------------------------------------------
1 | open Cmdliner
2 | open Db_engine
3 | open Db_engine.Types
4 |
5 | (* 定义文件名参数 *)
6 | let filename =
7 | let doc = "Input .sql file name" in
8 | Arg.(value & pos 0 (some string) None & info [] ~docv:"FILENAME" ~doc)
9 |
10 | (* 读取文件内容的函数 *)
11 | let read_file filename =
12 | try
13 | let ch = open_in filename in
14 | let content = really_input_string ch (in_channel_length ch) in
15 | close_in ch;
16 | Some content
17 | with _ -> None
18 |
19 | let eval_sql: (statement->table) = function
20 | | Select (cols, from, join, where) ->
21 | let table = Database.load_table (from ^ ".csv") in
22 | if join = None then
23 | Engine.execute (Select (cols, table, where))
24 | else
25 | let (from2, on) = Option.get join in
26 | let table2 = Database.load_table (from2 ^ ".csv") in
27 | let joined_table = Engine.execute (Join (table, table2, on)) in
28 | Engine.execute (Select (cols, joined_table, where))
29 | | CreateTable (name, columns) ->
30 | Engine.execute (CreateTable (name, columns))
31 | | InsertInto (table, columns, values) ->
32 | let table = Database.load_table (table ^ ".csv") in
33 | let result = Engine.execute (InsertInto (table, columns, values)) in
34 | Database.save_table table;
35 | result
36 | | Update (table, column, value, where) ->
37 | let table = Database.load_table ( table ^ ".csv" ) in
38 | Engine.execute (Update (table, column, value, where))
39 | | DeleteFrom (table, where) ->
40 | let table = Database.load_table (table^".csv") in
41 | Engine.execute (DeleteFrom (table, where))
42 | | ShowTables -> Engine.execute ShowTables
43 | | DropTable table -> Engine.execute (DropTable table)
44 | | LoadObject table -> Engine.execute (LoadObject table)
45 | | StoreObject table -> Engine.execute (StoreObject table)
46 | | Exit -> exit 0
47 |
48 | (* 交互式终端 *)
49 | let rec repl () =
50 | try
51 | Printf.printf ">>> ";
52 | let line = read_line () in
53 | let lexbuf = Lexing.from_string line in
54 | let parsed_expr = Parser.program Lexer.token lexbuf in
55 | let result = eval_sql parsed_expr in
56 | Printf.printf "%s\n" (Types.string_of_table result);
57 | repl ()
58 | with
59 | | Lexer.Lexing_error msg -> Printf.printf "Lexer error: %s\n" msg; repl ()
60 | | Parsing.Parse_error -> Printf.printf "Parser error\n"; repl ()
61 | | End_of_file -> ()
62 |
63 | let main filename =
64 | match filename with
65 | | None ->
66 | Printf.printf "Welcome to the SQL REPL!\n";
67 | repl()
68 | | Some file ->
69 | match read_file file with
70 | | Some content -> (
71 | (* 按行执行.sql文件的内容,遇到错误就报错并进入repl *)
72 | let lexbuf = Lexing.from_string content in
73 | try
74 | while true do
75 | let parsed_expr = Parser.program Lexer.token lexbuf in
76 | let result = eval_sql parsed_expr in
77 | Printf.printf "%s\n" (Types.string_of_table result);
78 | done
79 | with
80 | | Lexer.Lexing_error msg -> Printf.printf "Lexer error: %s\n" msg; repl ()
81 | | Parsing.Parse_error -> Printf.printf "Parser error\n"; repl ()
82 | | End_of_file -> ())
83 | | None ->
84 | Printf.printf "Error: Unable to read file '%s'\n" file
85 |
86 | (* 命令行配置 *)
87 | let cmd =
88 | let doc = "A program that reads and processes a file" in
89 | let info = Cmd.info "sql" ~doc ~version:"1.0.0" in
90 | Cmd.v info Term.(const main $ filename)
91 |
92 | (* 运行程序 *)
93 | let () = exit (Cmd.eval cmd)
--------------------------------------------------------------------------------
/src/parser.mly:
--------------------------------------------------------------------------------
1 | /* parser.mly */
2 | /* Simple SQL statement parser */
3 | /* Tokens */
4 | %token IDENTIFIER FILE
5 | %token INT
6 | %token STRING
7 | %token FLOAT
8 | %token BOOL
9 | %token CREATE USE SHOW INSERT INTO SELECT UPDATE SET DROP DELETE FROM WHERE EXIT
10 | %token DATABASES DATABASE TABLES TABLE VALUES JOIN ON AS
11 | %token BEGIN TRANSACTION COMMIT ROLLBACK LOCK UNLOCK
12 | %token VIEW INDEX LOG
13 | %token LPAREN RPAREN COMMA SEMICOLON
14 | %token STAR DOT MOD EQUALS LESS GREATER LESS_EQUAL GREATER_EQUAL NOT_EQUAL PLUS MINUS TIMES DIVIDE
15 | %token EOF
16 | %token INT_TYPE STRING_TYPE FLOAT_TYPE BOOL_TYPE
17 | %token AND OR NOT ORDER BY LIMIT
18 |
19 | %start program
20 | %type program
21 |
22 | %% /* Grammar rules and actions */
23 |
24 | program:
25 | | statement SEMICOLON { $1 }
26 | | EOF { Exit }
27 |
28 | statement:
29 | | SELECT columns FROM FILE opt_join opt_where { Select($2, $4, $5, $6) }
30 | | CREATE TABLE FILE LPAREN table_columns RPAREN { CreateTable($3, $5) }
31 | | SHOW TABLES { ShowTables }
32 | | INSERT INTO FILE LPAREN columns RPAREN VALUES values { InsertInto($3, $5, $8) }
33 | | UPDATE FILE SET IDENTIFIER EQUALS value opt_where { Update($2, $4, $6, $7) }
34 | | DELETE FROM FILE opt_where { DeleteFrom($3, $4) }
35 | | DROP TABLE FILE { DropTable $3 }
36 | | EXIT { Exit }
37 |
38 | opt_join:
39 | | JOIN FILE ON expr { Some ($2, $4) }
40 | | { None }
41 |
42 | opt_where:
43 | | WHERE expr { Some $2 }
44 | | { None }
45 |
46 | table_columns:
47 | | column_def COMMA table_columns { $1 :: $3 }
48 | | column_def { [$1] }
49 |
50 | column_def:
51 | | IDENTIFIER dtype { ($1, $2) }
52 |
53 | columns:
54 | | STAR { ["*"] }
55 | | IDENTIFIER COMMA columns { $1 :: $3 }
56 | | IDENTIFIER { [$1] }
57 |
58 | dtype:
59 | | INT_TYPE { Int }
60 | | STRING_TYPE { String }
61 | | FLOAT_TYPE { Float }
62 | | BOOL_TYPE { Bool}
63 |
64 | values:
65 | | LPAREN values_def RPAREN values { $2 :: $4 }
66 | | LPAREN values_def RPAREN { [$2] }
67 |
68 | values_def:
69 | | value COMMA values_def { $1 :: $3 }
70 | | value { [$1] }
71 |
72 | value:
73 | | INT { VInt $1 }
74 | | STRING { VString $1 }
75 | | FLOAT { VFloat $1 }
76 | | BOOL { VBool $1 }
77 |
78 | expr:
79 | | value { Literal $1 }
80 | | IDENTIFIER { Column $1 }
81 | | expr PLUS expr { BinOp($1, "+", $3) }
82 | | expr MINUS expr { BinOp($1, "-", $3) }
83 | | expr TIMES expr { BinOp($1, "*", $3) }
84 | | expr DIVIDE expr { BinOp($1, "/", $3) }
85 | | expr MOD expr { BinOp($1, "%", $3) }
86 | | expr EQUALS expr { BinOp($1, "=", $3) }
87 | | expr LESS expr { BinOp($1, "<", $3) }
88 | | expr GREATER expr { BinOp($1, ">", $3) }
89 | | expr LESS_EQUAL expr { BinOp($1, "<=", $3) }
90 | | expr GREATER_EQUAL expr { BinOp($1, ">=", $3) }
91 | | expr NOT_EQUAL expr { BinOp($1, "<>", $3) }
92 | | expr AND expr { BinOp($1, "AND", $3) }
93 | | expr OR expr { BinOp($1, "OR", $3) }
94 | | LPAREN expr RPAREN { $2 }
95 | | NOT expr { Call("NOT", [$2]) }
96 | | IDENTIFIER LPAREN expr_list RPAREN { Call($1, $3) }
97 |
98 | expr_list:
99 | | expr COMMA expr_list { $1 :: $3 }
100 | | expr { [$1] }
101 |
--------------------------------------------------------------------------------