Skip to content

Commit 2425c3f

Browse files
committed
✨ Add schema declaration in SQLite
1 parent fe786cc commit 2425c3f

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

plugin/module.go

+42
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,12 @@ func (m *SQLiteModule) Create(c *sqlite3.SQLiteConn, args []string) (sqlite3.VTa
7575
return nil, errors.Join(errors.New("could not request the schema of the table from the plugin "+m.PluginPath), err)
7676
}
7777

78+
// Create the schema in SQLite
79+
err = createSQLiteSchema(c, dbSchema)
80+
if err != nil {
81+
return nil, errors.Join(errors.New("could not create the schema in SQLite"), err)
82+
}
83+
7884
// Initialize a new table
7985
table := &SQLiteTable{
8086
0,
@@ -86,6 +92,42 @@ func (m *SQLiteModule) Create(c *sqlite3.SQLiteConn, args []string) (sqlite3.VTa
8692
return table, nil
8793
}
8894

95+
// createSQLiteSchema creates the schema of the table in SQLite
96+
// using the sqlite3.SQLiteConn.DeclareVTab method
97+
func createSQLiteSchema(c *sqlite3.SQLiteConn, arg DatabaseSchema) error {
98+
// Initialize a string builder to efficiently create the schema
99+
var schema strings.Builder
100+
101+
// The table name is not important, we set it to x therefore
102+
schema.WriteString("CREATE TABLE x(")
103+
104+
// We iterate over the columns and add them to the schema
105+
for i, col := range arg.Columns {
106+
schema.WriteString(col.Name)
107+
schema.WriteByte(' ')
108+
switch col.Type {
109+
case ColumnTypeInt:
110+
schema.WriteString("INTEGER")
111+
case ColumnTypeString:
112+
schema.WriteString("TEXT")
113+
case ColumnTypeBlob:
114+
schema.WriteString("BLOB")
115+
case ColumnTypeFloat:
116+
schema.WriteString("REAL")
117+
}
118+
119+
// We add a comma if it's not the last column
120+
if i != len(arg.Columns)-1 {
121+
schema.WriteString(", ")
122+
}
123+
}
124+
schema.WriteString(");")
125+
126+
// We declare the virtual table in SQLite
127+
err := c.DeclareVTab(schema.String())
128+
return err
129+
}
130+
89131
// Connect is called when the virtual table is connected
90132
//
91133
// Because it's an eponymous-only module, the method must be identical to Create

0 commit comments

Comments
 (0)